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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With