Parallel API Calls with `all` Effect in Redux-Saga
Illustrate how to perform multiple API calls in parallel by leveraging the `all` effect in Redux-Saga, effectively improving the efficiency of fetching data when multiple pieces of data can be requested concurrently.
import { call, put, all } from 'redux-saga/effects';
First, import the necessary functions from redux-saga. `call` is used to call the API, `put` to dispatch actions, and `all` to run calls in parallel.
function* fetchUserData(action) {
try {
const [user, posts] = yield all([
call(api.fetchUser, action.userId),
call(api.fetchPosts, action.userId)
]);
yield put({type: 'FETCH_USER_DATA_SUCCESS', user, posts});
} catch (error) {
yield put({type: 'FETCH_USER_DATA_FAILURE', error});
}
}
This generator function (saga) fetches user data and posts in parallel by using the `all` effect. `call` invokes the API functions, and the results are destructured into `user` and `posts`. `put` dispatches the success or failure actions.