Redux not updating right after dispatch in functional components

Viewed 684

Recently I decided to change my code from class to functional components. I'm using redux, axios and axiosMiddleware. Since I started changing to functional components I noticed something strange. See the following example which is a request using a dispatch (I'm using connect and mapDispatchToProps):

const getUserActivity = () => {
 await props
      .get(displayDateString)
      .then((response) => {
        console.log(response); //prints response
        console.log(props.activity); //prints part of the redux that should be updated
      })
      .catch((error) => console.log('error ' + error));
}
const mapDispatchToProps = (dispatch) => ({
  get: (date) => dispatch(ActivityReportActions.get(date))
})

My problem here is, when I get the response after "then" the redux does not get immediately updated, only afterwards. "console.log(props.activity)" prints the previous state, and in some cases I prefer to access the redux right after the response. Does anyone have any idea why this is happening in functional components and not in class components? If yes, is there a solution which does not require using useEffect()?

Thank you!

1 Answers

It is impossible to read new values from props immediately after dispatching. React hasn't had a chance to re-render yet.

If you need to read the latest state immediately after a dispatch, you'll have to write the logic as a thunk, which has access to getState:

https://redux.js.org/usage/writing-logic-thunks#accessing-state

Related