Fetching Data with Redux Saga
Demonstrate how to use Redux Saga for fetching data from an API, using `call` to make the request and `put` to dispatch the result.
import { call, put, takeLatest } from 'redux-saga/effects';
import axios from 'axios';
// Action Types
const FETCH_DATA_REQUEST = 'FETCH_DATA_REQUEST';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';
Define Redux action types for handling API call states and import necessary functions from redux-saga and axios for making http requests.
// API call function
function fetchDataAPI() {
return axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => response.data)
.catch(error => { throw error; });
}
Function to call the API using axios. On success, it returns the response data. In case of an error, it throws an error.
// Worker Saga
function* fetchDataSaga() {
try {
const data = yield call(fetchDataAPI);
yield put({ type: FETCH_DATA_SUCCESS, data });
} catch (error) {
yield put({ type: FETCH_DATA_FAILURE, error });
}
}
The worker saga uses call to invoke fetchDataAPI. Upon successful API call, it dispatches FETCH_DATA_SUCCESS with data. In case of an error, it dispatches FETCH_DATA_FAILURE.
// Watcher Saga
function* watchFetchDataSaga() {
yield takeLatest(FETCH_DATA_REQUEST, fetchDataSaga);
}
Watcher saga that triggers worker saga on FETCH_DATA_REQUEST actions. Using takeLatest ensures that it only responds to the latest request if multiple are made in a short time.
import { all, fork } from 'redux-saga/effects';
// Root saga
export default function* rootSaga() {
yield all([
fork(watchFetchDataSaga),
// Add other sagas here
]);
}
Root saga to aggregate all sagas including the watcher saga for fetching data. Other sagas can be added similarly using fork within the all effect.