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:
- Cleaner codebase (but may be overhead on smaller applications)
- Separation of "dummy" actions with all required information to perform requests and actual API middleware
- Request parameters are visible directly in redux dev tools
- Possible to easily
debounce
, throttle
fetches which may be really tricky with redux-thunk
- Possible to easily combine actions (wait for another event/fetch, chain events)
- Possible to stop running tasks
From 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.