I keep reading that I should use redux-thunk or redux-saga to handle side effects. Why not simply use action creators like that to dispatch multiple actions :
function loadProductActionCreator(dispatch) {
dispatch({
type: 'load_product',
})
fetch('api/product').then(
function (r) {
return r.json();
}
)
.then(function (res) {
dispatch({
type: 'loaded_product',
data: res
})
})
}
I tried that and it worked (complete code). So I guess there must be some inconvenients I'm not aware of.
Redux Saga. In thunk, action creator does not return an object, it returns a function, In the saga, it allows you to send action normally. but it has a watcher. whenever a particular action gets dispatched, the watcher catches it.
But on the other hand, for bigger projects, Redux-Thunk may sometimes get you in trouble, as it can be hard to scale if your side effect or asynchronous logic increases, whereas in the case of Redux-Saga, it comes power-packed with some amazing things such as concurrent side effects, canceling side effects, debouncing ...
redux-saga is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, easy to test, and better at handling failures.
Saga works like a separate thread or a background process that is solely responsible for making your side effects or API calls unlike redux-thunk, which uses callbacks which may lead to situations like 'callback hell' in some cases. However, with the async/await system, this problem can be minimized in redux-thunk.
You code is similar to what thunk does.
As per redux
docs, actions should be pure. And they should always return same values for same input parameters. By using fetch
you are allowing action to return not specific value, rather value from server and that mean action response may vary upon time.
That is called side effects. And it's something what shouldn't be in redux actions by default.
But why?
Yes, you can type it inside action like you have, in small apps it does not matter.
In larger application there are benefits of using redux-saga
:
actions are predictable, they just return payload like
{
type: 'FETCH_POSTS',
params: {
category: 'programming'
}
}
and then you build middleware which will take actions with all data required to perform request to real API
Possible advantages:
debounce
, throttle
fetches which may be really tricky with redux-thunkFrom personal experience, on one project (larger codebase) we have started with redux-thunk
, but later we needed to integrate more advanced features, like throttle, and some dependencies between actions. So we rewrote everything to redux-saga
and it worked well for us.
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