Reputation: 134
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!
Upvotes: 2
Views: 3848
Reputation: 451
If the logic is in your component not in a reducer so a better approach is to access the store from the component immediately as It'll contain the new value which hasn't made it yet to the component
import store from "../../redux/configureStore"
const requiredState = store.getState()[path of the required value];
I'm not sure if this is an anti-pattern though.
Upvotes: 0
Reputation: 67577
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
Upvotes: 4