travelboy
travelboy

Reputation: 2697

How to react to redux action without changing state

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()?

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

Answers (1)

Simon Laroche
Simon Laroche

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

Related Questions