Source:  Twitter logo

is there a way how to call method on variable change(state). How to get List which components changed ?

 componentDidUpdate(prevProps, prevState) {

    const {ID} = this.state
        if (this.ID !== this.previousID || this.cmbID !== this.previoudcmbID) {
            if(this.ID !== undefined && this.cmbID !== undefined)
            {
                this.reload3();

            //  console.log(this.prevProps)
                console.log(this.state.settings[0])
                console.log(this.prevState.settings[0])

            }



    }
    this.prevState = this.state;
}

Finally solved

componentDidUpdate(PrevProps, prevState){
if(this.state.cmbID !== prevState.cmbID){

    this.reload2()
}   
if(this.state.ID !== prevState.ID){

    this.reload3()
}
}
3 users liked answer #0dislike answer #03
Bobek profile pic
Bobek

if you are using this.setState({value: "newValue"}) you can use its other form which is

this.setState({}, callback) where callback will be having new values after state updated and you can handle it somehow there in more elegant way. Pseudo code below

<div onClick={this.handler} />
handler = () => this.setState({value: "newValue}, () => console.log(this.state.value))
2 users liked answer #1dislike answer #12
Shiroo profile pic
Shiroo

You need not maintain a prevState, if the variable that needs to be monitored is either in state or props, you can just make use of componentDidUpdate lifecycle hook to do the same

componentDidUpdate(prevProps, prevState) {

        const {ID, cmbID} = this.state
        const {ID: prevId, cmbID: prevCmbId} = prevState;
        if (ID !== prevId || cmbID !== prevCmbId) {
            if(typeof ID !== 'undefined' && typeof cmbID !== 'undefined')
            {
                this.reload3();

                console.log(prevProps)
                console.log(this.state.settings[0])
                console.log(prevState.settings[0])

            }
    }
}
1 users liked answer #2dislike answer #21
Shubham Khatri profile pic
Shubham Khatri

Copyright © 2022 QueryThreads

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