3

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

themaster
  • 345
  • 6
  • 15
  • I guess I could just add authCheck: () => checkApiStatus()(dispatch, store.getStore) and import the store to the container. It looks like Im doing something wrong though. – themaster Apr 08 '18 at 02:42
  • 1
    I'm trying to figure this out too. Here is a popular related question about thunks: https://stackoverflow.com/q/35667249/470749 – Ryan Apr 12 '20 at 14:46

1 Answers1

2

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())
  }
}
Moti Korets
  • 3,738
  • 2
  • 26
  • 35