Search code examples
reactjsreact-nativereduxredux-thunk

Redux getState in action not working


I'm getting a bit confused with getState() in redux. I am using the thunk middleware.

I have an auth action which is an async action. But I have an action which runs before which checks if a token exists in state and if its still valid.

My problem is i can't seem to check the state when I have called the action. Thought I could just use getState but that doesn't seem to be a function.

container.js

componentDidMount() {
  this.props.authCheck()
}
...
function mapDispatchToProps(dispatch) {
  return {
    authCheck: () => checkApiStatus()(dispatch)
  }
}

Action.js

export const checkApiStatus = () => (dispatch, getState) => {
  const expires_at = getState().api.expires_at
  if (!expires_at || isDateGreater(expires_at)) {
    // dispatch async action
    dispatch(apiAuth())
  }
  return
}

Anyone have any ideas. Or perhaps better way of implementing something like this?

Thanks


Solution

  • The problem is you explicitly calling the returned function in you mapDispatchToProps method and passing only one argument. Instead call dispatch(checkApiStatus()) then redux-thunk will take care of passing the right arguments to the returned method. Should look like this

    function mapDispatchToProps(dispatch) {
      return {
        authCheck: () => dispatch(checkApiStatus())
      }
    }