diff --git a/src/index.spec.tsx b/src/index.spec.tsx index 6325c62..9e30316 100644 --- a/src/index.spec.tsx +++ b/src/index.spec.tsx @@ -112,16 +112,35 @@ describe('useSagaReducer()', () => { } } + if (action.type === 'SET') { + return { + count: action.payload + } + } + return state }) function* increment() { + const {count} = yield select() + testState = count + } + + function* incrementAsync() { const state = yield select() - testState = state + yield put({ + type: 'SET', + payload: state.count + 1 + }) + + yield delay(0) + const {count} = yield select() + testState = count } function* testSaga() { yield takeEvery('INCREMENT', increment) + yield takeEvery('INCREMENT_ASYNC', incrementAsync) } function TestUseSagaReducer() { @@ -139,22 +158,41 @@ describe('useSagaReducer()', () => { > TEST + ) } const {getByTestId} = render() const button = getByTestId('button') + const buttonAsync = getByTestId('button-async') fireEvent.click(button) await act(flushPromiseQueue) - expect(testState).toEqual({count: 2}) + expect(testState).toEqual(2) fireEvent.click(button) await act(flushPromiseQueue) - expect(testState).toEqual({count: 3}) + expect(testState).toEqual(3) + + fireEvent.click(buttonAsync) + await act(flushPromiseQueue) + // Add a second flush here, once to wait for microtasks queue from put, + // second one to wait for timer queue from delay task + await act(flushPromiseQueue) + + expect(testState).toEqual(4) }) it('provides context values in sagas passed to provider', async () => { diff --git a/src/index.tsx b/src/index.tsx index f967169..0221064 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -4,7 +4,6 @@ import React, { useMemo, useEffect, useContext, - useLayoutEffect, Reducer, ReducerState, ReducerAction, @@ -29,9 +28,6 @@ export const SagaProvider: React.FC = (props) => { return } -const useIsomorphicLayoutEffect = - typeof window !== 'undefined' ? useLayoutEffect : useEffect - export function useSagaReducer< S extends Saga, R extends Reducer, @@ -50,7 +46,7 @@ export function useSagaReducer< ) const stateRef = useRef(state) - useIsomorphicLayoutEffect(() => { + useEffect(() => { stateRef.current = state }, [state]) @@ -60,8 +56,10 @@ export function useSagaReducer< >> = useMemo(() => { const channel = stdChannel() const dispatch = (action: ReducerAction) => { - setImmediate(channel.put, action) reactDispatch(action) + Promise.resolve().then(() => { + channel.put(action) + }) } const getState = () => stateRef.current