Reputation: 1971
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.
Upvotes: 5
Views: 1195
Reputation: 7767
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.
Upvotes: 5
Reputation: 11
You are kind of replicating redux-thunk here. A pure redux action creator should return an action object to be dispatched and not dispatch an action itself (see redux doc on action creator).
To better understand why your technic is a replication of redux-thunk, look at this post from its author
Upvotes: 1