Reducer sagan selectors, how do I access state from a saga?

Similar questions were asked before, but the answers didn’t help me at all.

What is an abbreviation selector?

How to get something from state / store inside redux-saga function?

I think I have a different setting, since I cannot access the state from my saga.

I tried to do:

const getList = store => store; const getList = state=> state; 

both return undefined .

My store looks like this ...

 export default function createStoreWithMiddleware() { const sagaMiddleware = createSagaMiddleware(); const loggerMiddleware = createLogger(); const middleware = [sagaMiddleware, loggerMiddleware]; const persistedState = localStorage.getItem('reduxState') ? JSON.parse(localStorage.getItem('reduxState')) : {}; const store = createStore(reducer, persistedState, compose( applyMiddleware(...middleware) )); store.subscribe(() => { localStorage.setItem('reduxState', JSON.stringify(store.getState())); }); sagaMiddleware.run(rootSaga); return store; } 

And I want to access my list in this saga:

 function* selectTender(action) { try { const response = yield Api.getTenderById(action.payload); yield put({type: 'SELECT_TENDER_SUCCEEDED', currentTender: response}); const list = yield select(getList); yield put({type: 'FETCH_CHAPTERS', chaptersList: list, tenderId: response.id}); } catch (err) { yield put({type: 'SELECT_TENDER_FAILED', message: err.message}); } } export function* watchSelectTender(){ yield takeEvery('SELECT_TENDER', selectTender); } 

But, as I said, both state and store undefined.

So, how do I access my store (or fortune) in the saga?

+5
source share
1 answer

For this you will need to use a selector. I will give a simple example. Create a selectors.js file and add the fields you want to select from your store, as shown below.

 export const username = (state) => state.user.name; 

Then in your saga import the selector as,

 import * as selectors from './selectors'; 

and when you need username in your saga, you can just do

 import {select} from 'redux-saga/effects'; ... ... function *sampleSaga(params) { const username = yield select(selectors.username); } 

the username constant in sampleSaga will now hold the username value from state.

+11
source

Source: https://habr.com/ru/post/1266869/


All Articles