Skip to content

Instantly share code, notes, and snippets.

@davekiss
Created January 31, 2017 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davekiss/8d49ee786578dd469f9cf66991f64cad to your computer and use it in GitHub Desktop.
Save davekiss/8d49ee786578dd469f9cf66991f64cad to your computer and use it in GitHub Desktop.
Checking existing state in a Redux Saga
import { takeEvery } from 'redux-saga';
import { put, select } from 'redux-saga/effects';
/*
* Select data from state. The return object depends on your state shape
*/
export const getLessons = state => state.lessons;
/*
* Our worker Saga: will perform the async lessons/EDIT task
*/
export function* editLessonAsync(action) {
const { id, title } = action.lesson;
const lessons = yield select(getLessons);
/*
* Arbitrarily dispatch a lessons/NEW event if the lesson we're editing exists in state.
*/
if ( Object.keys(lessons).includes(id) ) {
yield put( 'lessons/NEW' );
}
}
/*
* Our watcher Saga: spawn a new editLessonAsync task on each lessons/EDIT
*/
export function* watchEditLesson() {
yield takeEvery('lessons/EDIT', editLessonAsync);
}
/*
* Single entry point to start all Sagas at once
*/
export default function* rootSaga() {
yield [
watchEditLesson(),
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment