1

I know that react will not update the state immediately when you call setState. In this example how can i access the updated state ?

    changeInputHandler(e) {
        let value;
        let name = e.target.name;
        if(e.target.type === "checkbox") {
            value = e.target.checked;
        } else {
            value = e.target.value;
        }
        
        this.setState({
            [name]: value
        });

        //How can i use updated state here?
    } 

and i know that one solution is to use setTimeout, but is there any alternative?

MORA
  • 137
  • 1
  • 8
  • 2
    Can't you use `value` directly? If you want to run some code after the `setState` has finished updating, see this might help https://stackoverflow.com/questions/34687091/can-i-execute-a-function-after-setstate-is-finished-updating – Kartoos Feb 20 '22 at 10:50
  • 1
    I have done, only functional react, but I understood your issue, we can use useRef which is synchronous unlike stateUpdate which is async, another alternative may be you have to move what you want to do on input change in useEffect. Thanks – Wasit Shafi Feb 20 '22 at 10:52
  • thanks @WasitShafi, i change the class component to functional component and use useEffect. – MORA Feb 20 '22 at 10:57

1 Answers1

1

One way you deal with this is you just use the object you will set to the new state as you already have it in that scope, so:

changeInputHandler(e) {
    let value;
    let name = e.target.name;
    if(e.target.type === "checkbox") {
        value = e.target.checked;
    } else {
        value = e.target.value;
    }
    
    this.setState({
        [name]: value
    });

    //How can i use updated state here?
} 

If you rewrite it as:

changeInputHandler(e) {
        let value;
        let name = e.target.name;
        if(e.target.type === "checkbox") {
            value = e.target.checked;
        } else {
            value = e.target.value;
        }
        
        const newState = {
            ...this.state,
            [name]: value
        };
        
        this.setState(newState);

        //use newState here for whatever you need
    } 

Assuming you have access to the current state via the this.state.

Silidrone
  • 1,471
  • 4
  • 20
  • 35