Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "fix(react-utilities): fix dispatcher behavior",
"packageName": "@fluentui/react-utilities",
"email": "[email protected]",
"dependentChangeType": "patch"
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,27 @@ describe('useControllableState', () => {
expect(result.current[0]).toBe(initialState);
});

it('should call setState() with a value when is controlled', () => {
const spy = jest.fn();
const { result } = renderHook(() =>
useControllableState({ state: 'foo', defaultState: undefined, initialState: '' }),
);

const [, setState] = result.current;

act(() => {
setState(prevState => {
spy(prevState);
return prevState;
});
});

expect(result.current[0]).toEqual('foo');

expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith('foo');
});

it.each([
['', true],
['factory', () => true],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ export type UseControllableStateOptions<State> = {
initialState: State;
};

function isFactoryDispatch<State>(newState: React.SetStateAction<State>): newState is (prevState: State) => State {
return typeof newState === 'function';
}

/**
* @internal
*
Expand All @@ -45,17 +49,29 @@ export const useControllableState = <State>(
}
return isInitializer(options.defaultState) ? options.defaultState() : options.defaultState;
});
return useIsControlled(options.state) ? [options.state, noop] : [internalState, setInternalState];

// Heads up!
// This part is specific for controlled mode and mocks behavior of React dispatcher function.

const stateValueRef = React.useRef<State | undefined>(options.state);

React.useEffect(() => {
stateValueRef.current = options.state;
}, [options.state]);

const setControlledState = React.useCallback((newState: React.SetStateAction<State>) => {
if (isFactoryDispatch(newState)) {
newState(stateValueRef.current as State);
}
}, []);

return useIsControlled(options.state) ? [options.state, setControlledState] : [internalState, setInternalState];
};

function isInitializer<State>(value: State | (() => State)): value is () => State {
return typeof value === 'function';
}

function noop() {
/* noop */
}

/**
* Helper hook to handle previous comparison of controlled/uncontrolled
* Prints an error when isControlled value switches between subsequent renders
Expand Down