getState in redux-saga?
JavascriptReactjsReduxRedux SagaJavascript Problem Overview
I have a store with a list of items. When my app first loads, I need to deserialize the items, as in create some in-memory objects based on the items. The items are stored in my redux store and handled by an itemsReducer
.
I'm trying to use redux-saga to handle the deserialization, as a side effect. On first page load, I dispatch an action:
dispatch( deserializeItems() );
My saga is set up simply:
function* deserialize( action ) {
// How to getState here??
yield put({ type: 'DESERISLIZE_COMPLETE' });
}
function* mySaga() {
yield* takeEvery( 'DESERIALIZE', deserialize );
}
In my deserialize saga, where I want to handle the side effect of creating in-memory versions of my items, I need to read the existing data from the store. I'm not sure how to do that here, or if that's a pattern I should even be attempting with redux-saga.
Javascript Solutions
Solution 1 - Javascript
you can use select effect
import {select, ...} from 'redux-saga/effects'
function* deserialize( action ) {
const state = yield select();
....
yield put({ type: 'DESERIALIZE_COMPLETE' });
}
also you can use it with selectors
const getItems = state => state.items;
function* deserialize( action ) {
const items = yield select(getItems);
....
yield put({ type: 'DESERIALIZE_COMPLETE' });
}
Solution 2 - Javascript
Select effect does not help us if we in a callback functions, when code flow is not handled by Saga. In this case just pass dispatch
and getState
to root saga:
store.runSaga(rootSaga, store.dispatch, store.getState)
And the pass parameters to child sagas
export default function* root(dispatch, getState) {
yield all([
fork(loginFlow, dispatch, getState),
])
}
And then in watch methods
export default function* watchSomething(dispatch, getState)
...