Push this.props’ value to the state of child component

I need to push values which are coming from props to the state.

I have a value, this.props.faculty = 19 which comes to me from parent. Now, each time I get a value from parent, I want to push it to my state in child. So, in the end in my child I would have something like this:

this.state.faculties = [19, 20, 13 etc]

How can I do that? I use React.js with TypeScript.

I tried:

componentDidUpdate() {
  this.setState({ ...this.state, faculties: this.props.faculty, });
}

Answer

componentDidUpdate is called after every re-render, since you use setState in it without conditional check, it will result in an infinite loop

You must check if the previous and currentValue from props is different and only then push it. Also use functional setState to update the state by adding an item

componentDidUpdate(prevProps) {
  if (prevProps.faculty !== this.props.faculty) {
      // This assumes, faculty cannot contain duplicate values in simultaneous updates
      this.setState(prevState=> ({ 
           faculties: prevState.faculties.concat([this.props.faculty])
      }));
  }
}