Manikanta
Manikanta

Reputation: 335

How to setState the props value in ComponentDidUpdate in react-native?

componentDidUpdate(){
 var date = this.props.navigation.state.params.selected_date

 this.setState({
   sleepinputs_date: date
 })
}

When I try to setState the props value it throws an error "enter image description here

Upvotes: 2

Views: 4407

Answers (2)

Lee Marreros
Lee Marreros

Reputation: 355

According to react docs, you will get an argument in componentDidUpdate. You can set state only if you use a conditional like the following.

  componentDidUpdate(prevProps) {
//    Typical usage (don't forget to compare props):
      if (this.props.userID !== prevProps.userID) {
        this.fetchData(this.props.userID);
      }
    }

Basically you are comparing the old props with the new ones. Only if they are different, you can keep updating or modifying the value. If previous props are the same as current props, why you botter to set state them again.

Upvotes: 1

Sanzhar Dan
Sanzhar Dan

Reputation: 393

You had created infinite state update. Inside componentDidUpdate you update the state, when it updates the state, componentDidUpdate invokes again in this stuff keeps going without ending.

Upvotes: 3

Related Questions