Source:  Twitter logo

I want to know why when I dispatch action before my console log prints old state. if I do next: reducer.js

let initialState = { display: false };
const MyReducer = (state = initialState,action) => { 
  ...
  case 'SET_DISPLAY':
    return { update(state,{ display : {$set: action.display } }) }
    break;
  default:
    return state;
  break;
}

ActionCreator.js

let ActionCreator = {
  setDisplay(value) {
    return(dispatch,getState) {
      dispatch({ type: 'SET_DISPLAY',display: value})
    }
  }
};

app.js

componentDidMount(){
  this.props.dispatch(ActionCreator.setDisplay(true))
  // expected : true
  console.log(this.props.display)
  // prints : false.
}

const mapStateToProps = (state) => {
  display : state.display
}

but I can see changes in my redux dev-tools console. PD I use redux-thunk as Middleware.its just example,all my code seems good and works great,but,its a question. Why console logs old state instead a new state (its ilogic, if I dispatched an action before call logs) I will apreciate your answers,thanks.

This is because you are using redux-thunk and your dispatch happens aynchronously.

this.props.dispatch(ActionCreator.setDisplay(true)) will not set display true immediately.

Since you are not making a network request or anything async in that action why dont you change the action creator to

let ActionCreator = {
  setDisplay(value) {
    return { type: 'SET_DISPLAY',display: value};
  }
};

Now it will happen synchronously. Also dont put console log immediately after dispatching. As redux updates state, old state is not modified. Instead it creates a new state instance with updated value. This new value will be passed as props to your component via connect of react-redux. Try printing display in render() method, you will see that it is called twice and second one will display true.

1 users liked answer #0dislike answer #01
Subin Sebastian profile pic
Subin Sebastian

First, I would recommend not to rely on the fact that dispatching an action may be synchronous; design as if everything was asynchronous. When eventually you dispatch an async actions, you will be pleased to have your mindset ready for that.

Second, your action creator return a function (you must be using the thunk middleware), which is why you get this behaviour.


  componentDidMount(){
   startSomethingAsync();
  }

  componentDidUpdate(){
    if (!this.props.asyncCompleted) return;

    if(this.props.asyncResultFn) {
       this.props.dispatch({ type: ... value: VALUE_CONDITIONAL_TRUE}) 
    }
    else{
       this.props.dispatch({ type: ... value: VALUE_CONDITIONAL_FALSE}) 
    }
  }
1 users liked answer #1dislike answer #11
Sylvain profile pic
Sylvain

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).