Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling setState() in React from render method

Tags:

reactjs

redux

I am trying to reset React state variables (to default values) in a container using setState() method. But getting the following error

 Warning: setState(...): Cannot update during an existing state transition 
(such as within `render` or another component's constructor). Render methods 
 should be a pure function of props and state; constructor side-effects are an anti-pattern, 
 but can be moved to `componentWillMount`.

And finally: Maximum call stack size exceeded.

My code below:

resetMsg=()=>  {  
const company = this.state.company;
company.id = 0;
company.messages = [];    
this.setState({company: company});       
}

I am calling resetMsg() when variable in Redux state is true.

Code where I call resetMsg (The value of resetMessages is false initially and I need to reset React-state, when its true ):

    render() {
    if(this.props.resetMessages){           
        this.resetMsg();           
    }
like image 370
user8125765 Avatar asked Jan 12 '18 12:01

user8125765


1 Answers

componentWillReceiveProps is deprecated now (since June'18)

You should use one of the alternatives presented in the react docs instead.

In your case I guess it could be justified to use the 'not so recommended' alternative 1 version that uses getDerivedStateFromProps, as you are just recomputing the state vars:

getDerivedStateFromProps(props, state) {
  if(props.resetMessages) {
    const company = Object.assign({}, state.company);
    company.id = 0;
    company.messages = [];    
    return {
      company: company
   }
}
like image 176
Larzan Avatar answered Sep 29 '22 13:09

Larzan