RyuH.
RyuH.

Reputation: 89

In react componentDidUpdate not updating state

I need to update my state (start_date) with the props that coming in to my component, but setState is not updating my state. Instead, I am getting a value of undefined.

Here's what I am doing in my code:

constructor(props) {
  super(props);
  this.state = {
    start_date: ''
  };
}

componentDidUpdate(prevProps, prevState) {
  console.log("prevProps ", prevProps)
  console.log("prevState ", prevState)
  if (prevProps.currentRelease != prevState.currentRelease) {
     console.log("Inside componentDidUpdate ")
     this.setState({
    //  start_date: prevProps.currentRelease.start
    });
  }
}

and here's a screenshot of my data that's coming in from the parent component passing it down to the child component:

data

I need to update start_date state with currentRelease.start (the red box)

Upvotes: 0

Views: 3243

Answers (2)

Predrag Davidovic
Predrag Davidovic

Reputation: 1566

Problem was, you were updating state with prevProps (with old one).

You should use this.props (current) props instand of prevProps:

Correct code:

this.setState({
//  start_date: this.props.currentRelease.start
});

Your wrong Code :

 this.setState({
//  start_date: prevProps.currentRelease.start
});

In you code I replaced prevProps with this.props.

Upvotes: 0

seunggabi
seunggabi

Reputation: 1822

I recommend this. instead of componentDidupdate

static getDerivedStateFromProps(props, state) {
    const { currentRelease } = props;

    if(currentRelease && currentRelease.start) {
        return { start_date: props.currentRelease.start }
    }

    return null;
}

reference: https://reactjs.org/docs/react-component.html#updating

Upvotes: 2

Related Questions