xploreraj
xploreraj

Reputation: 4362

How to change state in componentDidMount?

I have a react page and based upon an Axios call failure, I set error state to true which is false by default. When its true, I show an error. I tried to use componentDidMount for that as below:

componentDidMount() {
  const showError = this.state.saveError;
  if(showError) {
    setTimeout(() => {
      this.setState({
        saveError: false
      })
    }, 3000)
  }
}

But it doesn't seems to work as the error is always displayed once set to true. How do I fix it? Any other suggestion?

Thanks

Upvotes: 0

Views: 53

Answers (2)

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

Update the state in componentDidUpdate as the componentDidUpdate life cycle method will execute whenever there is an update in component.

Sample Code:

 componentDidUpdate() {
    const showError = this.state.saveError;
    if (showError) {
        setTimeout(() => {
            this.setState(prevState => {
                return {
                    ...prevState 
                    saveError: false
                }
            })
        }, 3000)
    }
}

Upvotes: 1

P4TRYK
P4TRYK

Reputation: 169

Please show your initialState. Please explain what are you trying to do here, because I don't see any Axios request.

Assign value of state to variable doesn't make any sense: const showError = this.state.saveError;

Upvotes: 0

Related Questions