It's simple to get access to the store inside a React component – no need to pass the store as a prop or import it, just use the connect function from React Redux, and supply a mapStateToProps function that pulls out the data you need. Then, inside the component, you can pass that data to a function that needs it.
redux state can be accessed as prop in a function by using below format. 1: import { connect } from 'react-redux'; // log accepts logMessage as a prop function log(props) { const { environment, logMessage } = props; console. debug('environment' + environment + logMessage ); .... }
getState. It helps you retrieve the current state of your Redux store.
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.
This is what "selector" functions are for. You pass them the entire state tree, and they return some piece of the state. The code that calls the selector doesn't need to know where in the state that data was, just that it was returned. See http://redux.js.org/docs/recipes/ComputingDerivedData.html for some examples.
Within a saga, the select()
API can be used to execute a selector.
I used an eventChannel to dispatch an action from a callback within the generator function
import {eventChannel} from 'redux-saga';
import {call, take} from 'redux-saga/effects';
function createEventChannel(setEmitter) {
return eventChannel(emitter => {
setEmitter(emitter)
return () => {
}
}
)
}
function* YourSaga(){
let emitter;
const internalEvents = yield call(createEventChannel, em => emitter = em)
const scopedCallback = () => {
emitter({type, payload})
}
while(true){
const action = yield take(internalEvents)
yield put(action)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With