Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run redux-thunk action without dispatch

I am using Redux to manage my app state, and I had an async action made with redux-thunk.

export const login = credentials => dispatch => {
   return doLogin(credentials).then(token => {
      localStorage.setItem('token', token)
      // this dispatch call was there before, but now it has gone,
      // because it is not necessary anymore
      // dispatch({ type: LOGIN_SUCCESS })
   })
}

The thing is that now I have an action which doesn't dispatch any actions into store, just does its job about login and storing token.

Is it okay to have such kind of action? I am not feel so confident about this code, but I don't know how to make it better.

like image 335
just-boris Avatar asked Mar 23 '26 21:03

just-boris


1 Answers

You're asking for an opinion on something that doesn't have hard rules, but the rule of thumb is that actions should be a minimal description of something that happened in the application.

Thunkified actions in general are a workaround for this behavior, but in this case it's okay to have this kind of action because even though it doesn't have an effect on Redux state through a reducer, you're using (thunk) middleware to perform side effects, and middleware is designed to respond to actions.

The fact that you're triggering an 'upstream' action that isn't consumed by a reducer downstream doesn't really matter, although it might be a good practice to still dispatch({ type: 'LOGIN_REQUEST' }) at the start and dispatch({ type: 'LOGIN_SUCCESS'}) at the end just so the downstream application has a way to know what is going on if it wants to do something about it later on.

like image 154
Mike McG Avatar answered Mar 26 '26 09:03

Mike McG



Donate 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!