Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set state in lifecycle method React JS

Tags:

reactjs

I have React lifecycle method as follows:

componentWillReceiveProps(nextProps){
    if(this.props.totalVehicles !== nextProps.totalVehicles){
        this.setState({animation: "cartCount"}, () => setTimeout(() =>  this.setState({animation: null}), 1000));
    }
}

But that gives me:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Header component.

How to set state in the lifecycle methods without getting those errors?

like image 657
Boky Avatar asked Oct 16 '22 23:10

Boky


2 Answers

Although this is an old questions, i'll answer it for future references.

When using setState (which is asynchronous) via setTimeout, you have to remember to clear the timeout on componentWillUnmount. Otherwise, you might get to situations in which the setState is called after the element has already unmounted.

like image 154
Ofir Avatar answered Oct 21 '22 03:10

Ofir


How about setting it on componentWillUpdate? That way, you know that the component has mounted already. Docs here

If you want to set up initial state, do it in componentWillMount.

More lifecycle methods in here

like image 42
jamcreencia Avatar answered Oct 21 '22 03:10

jamcreencia