Skip to content

Commit

Permalink
Fixes #1
Browse files Browse the repository at this point in the history
  • Loading branch information
azmenak committed Dec 20, 2019
1 parent c9d1e02 commit 074f2ed
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,60 @@ describe('useSagaReducer()', () => {
expect(el.textContent).toBe('2')
})

it('saga updates the state available to yield select()', async () => {
let testState: any
const testReducer = jest.fn((state = {}, action: any) => {
if (action.type === 'INCREMENT') {
return {
count: state.count + 1
}
}

return state
})

function* increment() {
const state = yield select()
testState = state
}

function* testSaga() {
yield takeEvery('INCREMENT', increment)
}

function TestUseSagaReducer() {
const [, dispatch] = useSagaReducer(testSaga, testReducer, {count: 1})

return (
<div>
<button
data-testid='button'
onClick={() => {
dispatch({
type: 'INCREMENT'
})
}}
>
TEST
</button>
</div>
)
}

const {getByTestId} = render(<TestUseSagaReducer />)
const button = getByTestId('button')

fireEvent.click(button)
await act(flushPromiseQueue)

expect(testState).toEqual({count: 2})

fireEvent.click(button)
await act(flushPromiseQueue)

expect(testState).toEqual({count: 3})
})

it('provides context values in sagas passed to provider', async () => {
const testReducer = jest.fn((state = {}, action: any) => {
return state
Expand Down
8 changes: 8 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import React, {
useMemo,
useEffect,
useContext,
useLayoutEffect,
Reducer,
ReducerState,
ReducerAction,
Expand All @@ -28,6 +29,9 @@ export const SagaProvider: React.FC<SagaProdiderProps> = (props) => {
return <SagaContext.Provider {...props} />
}

const useIsomorphicLayoutEffect =
typeof window !== 'undefined' ? useLayoutEffect : useEffect

export function useSagaReducer<
S extends Saga<never[]>,
R extends Reducer<any, any>,
Expand All @@ -46,6 +50,10 @@ export function useSagaReducer<
)

const stateRef = useRef(state)
useIsomorphicLayoutEffect(() => {
stateRef.current = state
}, [state])

const sagaIO: Required<Pick<
RunSagaOptions<any, S>,
SagaIOKeys
Expand Down

0 comments on commit 074f2ed

Please sign in to comment.