Reputation: 11444
I wish to know what is the proper way in Redux Saga to achieve the following behavior:
I have successfully implemented it by using the following pattern (sorry I lack full code examples, it isn't available at the moment):
function* fetchData(dataType) {
const resp = yield call(MyApi.fetchData, dataType);
if(!resp.err) {
yield put(fetchDataSuccess, resp.data);
} else {
return resp.err;
}
}
function* mySaga() {
const errors = yield all([
call(fetchData, 'typeOne'),
call(fetchData, 'typeTwo),
call(fetchData, 'typeThree)
]);
// errors contains the returned errors
}
Is it the best way to achieve the desired effect?
Upvotes: 7
Views: 2297
Reputation: 2477
You can use fork
effect for sending the requests concurrently
https://redux-saga.js.org/docs/advanced/ForkModel.html
So your code will become like
function* fetchData(dataType) {
const resp = yield call(MyApi.fetchData, dataType);
if(!resp.err) {
yield put(fetchDataSuccess, resp.data);
} else {
return resp.err;
}
}
function* mySaga() {
yield fork(fetchData, 'typeOne');
yield fork(fetchData, 'typeTwo');
yield fork(fetchData, 'typeThree');
}
For error handling, you can throw the error from the generator and handle it in the main saga.
Upvotes: 2