Last active
January 21, 2018 17:36
-
-
Save ryanjyost/d5a3fa17252d8393f6d0fcd83cabf29f to your computer and use it in GitHub Desktop.
The sagas.js file for Dog Saga - Redux-Saga Beginner Tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { takeLatest, call, put } from "redux-saga/effects"; | |
| import axios from "axios"; | |
| // watcher saga: watches for actions dispatched to the store, starts worker saga | |
| export function* watcherSaga() { | |
| yield takeLatest("API_CALL_REQUEST", workerSaga); | |
| } | |
| // function that makes the api request and returns a Promise for response | |
| function fetchDog() { | |
| return axios({ | |
| method: "get", | |
| url: "https://dog.ceo/api/breeds/image/random" | |
| }); | |
| } | |
| // worker saga: makes the api call when watcher saga sees the action | |
| function* workerSaga() { | |
| try { | |
| const response = yield call(fetchDog); | |
| const dog = response.data.message; | |
| // dispatch a success action to the store with the new dog | |
| yield put({ type: "API_CALL_SUCCESS", dog }); | |
| } catch (error) { | |
| // dispatch a failure action to the store with the error | |
| yield put({ type: "API_CALL_FAILURE", error }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment