Reputation: 2697
How can I make a redux action have an effect without actually changing the state?
I am porting existing code to redux: when a logout button is clicked, an existing function logout()
makes an AJAX request that logs out the user. If that request fails, it calls alert('Logout failed');
In the ported code, the logout button calls an action creator which is implemented using redux-thunk
:
export function logout(email, pass, callback) {
return function(dispatch) {
axios.get('/logout')
.then(function(response) {dispatch({type: 'LOGOUT_SUCCESS'})})
.catch(function(error) {dispatch({type: 'LOGOUT_FAILURE', message: error.response.data})});
};
}
A reducer handles the LOGOUT_SUCCESS
action and removes the user object from the state, which is straight-forward. But should I handle the failure case and trigger the alert()
?
alert()
, but somehow I feel that this is not the right placealert()
and just return the same state... but that seems a bad idea because reducers should be pure functions with no side-effects.{messages: ['Login failed']}
and some other part of the code could react to this, throw the alert and call another action that removes the message from the state. But this seems unnecessarily complex.What pattern would make sense for such cases where you want to trigger an action through an event but not change the state, and you want to keep it out of the action creator?
Upvotes: 4
Views: 4156
Reputation: 77
If the only thing that happens when the login fails is the alert, just call it in the function there.
Remember, react is just plain JavaScript, don't try to force yourself into an ideology; these patterns are guidelines not rules.
You may want to check out redux-saga
, which handles redux side effects in a more declarative way than thunks.
Upvotes: 3