Quantcast
Channel: getState in redux-saga? - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Bayu for getState in redux-saga?

$
0
0

In addition to the answer from @Kokovin Vladislav, if we like to use typing of Typescript, we could use "defined typed hooks" pattern introduced by redux-toolkit on this doc: https://redux-toolkit.js.org/tutorials/typescript#define-typed-hooks.

So, in the app/hooks.ts file we have:

import { useDispatch, useSelector } from 'react-redux'import type { TypedUseSelectorHook } from 'react-redux'import type { RootState, AppDispatch } from './store'import { select } from 'redux-saga/effects'// Use throughout your app instead of plain `useDispatch` and `useSelector` ( From redux-toolkit docs )export const useAppDispatch: () => AppDispatch = useDispatchexport const useAppSelector: TypedUseSelectorHook<RootState> = useSelector// THIS IS THE ADDITIONAL SELECTOR!!!!!!!export function* appSelect<TSelected>( selector: (state: RootState) => TSelected, ): Generator<any, TSelected, TSelected> { return yield select(selector); }

Then in your generator function, you could do similar like this:

import { appSelect } from "app/hooks"function* deserialize( action ) {    const items = yield* appSelect(state => state.items);    ....    yield put({ type: 'DESERIALIZE_COMPLETE' });}

That way we have strong typing and intelisense of state on each call of appSelect().

Credit: https://github.com/redux-saga/redux-saga/issues/970#issuecomment-880799390


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>