We need a way to do async and side-effect type things due to actions inside of a redux application. Examples would be we need to log a person into our system due to a LOG_USER_IN action or we want to ask the server for some data due to a FETCH_COMMENTS action. Redux does not offer us a clean way to do this.
redux-saga offers us an interface and some helper functions for working with async and side-effect code via generator functions. Please see the generator functions docs for more information on generators in javascript.
The docs are very informative on how to use the package. Some of the highlights are:
- How to use the helper functions
- How to hook up a Redux action to redux-saga
- How to dispatch an action
We create two different generator functions, one for connecting to the actions and one for actually handling the response:
// This function is started over each time
// we call it with the action that triggered it
export function* fetchSetLoading(action: any) {
// we are using `put` to dispatch the action
// that is returned from `setLoadingResult`
// and we use `yield` to return it to the
// calling context
return yield put(setLoadingResult(action.isLoading));
}
// we say that every time we get an action of SET_LOADING
// we want to run the fetchSetLoading function
export function* setLoading() {
return yield takeLatest(SET_LOADING, fetchSetLoading);
}This article explains it better than I could ever!