State not updating when receiving new props (ReactJS)

State not updating when receiving new props (ReactJS)  #angularjs #reactjs

  • You initially set state to an empty array, so on first render it’ll be empty.
  • I would add that you should really determine if you need state to represent what you want to show on the page or if you can strictly use props.
  • you now have a shadow of the same data stored in state as well as props.
  • But after the async calls sends the props to the parent and that gets passed down, and it does hit the componentWillReceiveProps function.
  • Having ‘pure’ functional react components (components that only render based on what is in props) is always a good goal.

A parent component will pass an array into this child component. When I console.log(this.props.repairs) it shows me an array of 4. I am trying to update this.state.sortedDataList whenever the array of repairs is passed in. The console.log(this.state) is still showing sortedDataList as an empty array.

@ng_real_ninja: State not updating when receiving new props (ReactJS) #angularjs #reactjs

I’m new to React. I’m stuck on this, would really appreciate some help!

What am I doing wrong? Thanks so much, appreciate any help.

Answers from Jayce444 and Shubham are correct. I would add that you should really determine if you need state to represent what you want to show on the page or if you can strictly use props. Having ‘pure’ functional react components (components that only render based on what is in props) is always a good goal. – Brandon Roberts 2 hours ago

Why are you setting props to state? what good does that do for you? you now have a shadow of the same data stored in state as well as props. To add to that props are considered immutable meaning you don’t and shouldn’t change them. setting props to state like this is making your immutable data now mutable, which is an Anti-Pattern and is a big no no. Read this to understand more stackoverflow.com/a/28785276/2733506 – John Ruddell 1 hour ago

isn’t called on the first render. That is the reason that you don’t see any update in the state

“Invoked when a component is receiving new props. This method is not called for the initial render.”

Never mind, found my silly mistake! If anyone else gets stuck on this in the future…

State not updating when receiving new props (ReactJS)

You might also like More from author

Comments are closed, but trackbacks and pingbacks are open.