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

前端 未结 3 374

How do I access the redux state inside a saga function?

Short answer:

import { select } from \'redux-saga/effects\';
...
let data =          


        
3条回答
  •  隐瞒了意图╮
    2020-12-22 21:06

    As @markerikson already says, redux-saga exposes a very useful API select() to invoke a selector on the state for getting some part of it available inside the saga.

    For your example a simple implementation could be:

    /*
     * Selector. The query depends by the state shape
     */
    export const getProject = (state) => state.project
    
    // Saga
    export function* saveProjectTask() {
      while(true) {
        yield take(SAVE_PROJECT);
        let project = yield select(getProject); // <-- get the project
        yield call(fetch, '/api/project', { body: project, method: 'PUT' });
        yield put({type: SAVE_PROJECT_SUCCESS});
      }
    }
    

    In addition to the suggested doc by @markerikson, there is a very good video tutorial by D. Abramov which explains how to use selectors with Redux. Check also this interesting thread on Twitter.

提交回复
热议问题