Skip to content

Instantly share code, notes, and snippets.

@MosesEsan
Created February 13, 2017 13:21
Show Gist options
  • Save MosesEsan/cc52fbd9f4440fdaffc3483dc6b127ae to your computer and use it in GitHub Desktop.
Save MosesEsan/cc52fbd9f4440fdaffc3483dc6b127ae to your computer and use it in GitHub Desktop.
Redux-Saga Example
import { take, put, fork, call, race } from 'redux-saga/effects';
function fetchDataApi(id) {
return fetch(url, { method: 'GET' })
.then((response) => response.json())
.catch((error) => error.json())
}
import { FETCH_DATA } from './types';
import { fetchDataSuccess, fetchDataFailure } from './actions';
// generator basic
// yield is like a red light in your code
// code stops until that line resolves
function* handleFetchData() {
// has to be in a while statement, I don't know why to be honest
while (true) {
try {
// take method listens for action types
// you can either use just yield take if you want an action to just trigger
// or assign it to a variable
let id = yield take(FETCH_DATA);
or
yield take(FETCH_DATA);
// weird way of calling an API imo but thats the saga way
let response = yield call(fetchDataApi, id);
// whatever error handling you want
if (response.status === 200) {
// put = calling action creator
yield put(fetchDataSuccess(response.data));
} else {
yield put(fetchDataFailure(error));
}
} catch (error) {
// any other errors, fire failure action
yield put(fetchDataFailure(error));
}
}
}
// export the saga to use with the saga-middleware
export function* exampleSaga() {
// combine all the generators into one saga, similar to combineReducers
yield [
fork(handleFetchData)
]
}
// some notes
// you can yield multiple calls
let [ friends, tweets ] = yield [
call(fetchFriendsApi),
call(fetchTweetsApi)
]
// you can race different calls
let { success, error } = yield race({
success: take(FETCH_DATA_SUCCESS),
error: take(FETCH_DATA_FAILURE)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment