简体   繁体   中英

How to get latest state value in ReactJS function?

Below function is called from 2-3 places depending on the situation. I am making api call according to the value in my state like this:

myFunction = () => {
    # do something
    const { myVariable } = this.state;
    if (!myVariable.item) {    // myVariable.item is not getting latest variable
        makeAPICall().then(data => {
            myVariable.item = data;
            this.setState({ myVariable });    // setting in state here
        });
    }
}

After one call to the above function, the state myVariable should be set with item, but when it is called again just after that, myVariable.item is undefined.

What can I do to get the latest value from my state to prevent another api call?

Problem: State Mutation

Your variable myVariable is an object reference to the object in this.state.myVariable . You cannot assign to it like myVariable.item = data because this is an illegal mutation of state.

Solution

You need to create a new object, which you can do with object spread syntax.

myFunction = () => {
    const { myVariable } = this.state;
    if (!myVariable.item) {
        makeAPICall().then(data => {
            this.setState({ 
               myVariable: {
                  ...myVariable, // copy all properties
                  item: data, // override item property
               }
            });
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM