Home > Net >  Accessing state after re-rendering - React
Accessing state after re-rendering - React

Time:02-20

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?

CodePudding user response:

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.

  • Related