Call function after dispatch from redux has finished

KellysOnTop23 picture KellysOnTop23 · Nov 30, 2017 · Viewed 22.4k times · Source

All around it but not quite as I have enough of an idea of redux-thunk and of react-router but I am not getting this seemingly simple idea of:

Call a change in route programmatically via <Route/>'s history.push('/') after an action has finished dispatching to the store, this to happen when a button is pushed.

const LoggerRedux = ({stateProp, LogIn}) => {
    return(
      <div>
        <h2>Here is the button. Use this to login</h2>
        <Route render={({ history}) => (
          <button
            type='button'
            onClick={

            //Something that calls {LogIn}
            //and then the history.push('/')

            }
            >
            Log yo Arse Inn
          </button>
        )}>

        </Route>
      </div>
    )
}

const mapStateToProps = (state) => {
  return {
    stateProp : state
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    LogIn : () => dispatch({
      type : 'AUTHENTICATE'
    }),
    LogOut : (bool) => dispatch({
      type : 'LOGGED_OUT',
      bool
    })
  }
}
const LoginConn = connect( mapStateToProps, mapDispatchToProps)(LoggerRedux);

Layman explanations and examples of all things I mentioned/tagged would also be nice

Answer

Hashibuto picture Hashibuto · Nov 30, 2017

Have your action creator return a promise. This way when you invoke it, you can use .then() and in your then handler you can push a new address to the history.

Thunks will return functions normally, but a promise differs in that you can act after completion.

Example:

static myActionCreator(somevar) {
  return dispatch => {
    return new Promise((resolve, reject) => {
      dispatch({
        type: "myaction",
        something: somevar
      });

      resolve()
    });
  }
}

So in this case, your thunk returns a promise. Then when you invoke like this:

this.props.myActionCreator(somevar)
.then(() => {
  this.props.history.push('/winning')
})

This thunk is just dispatching an action, but you could have some async call in there that has a callback, etc. and you resolve on completion.