React Child Component Not Updating After Parent State Change

There are two issues with your code.

Your child component’s initial state is set from props.

this.state = {
  data: props.data
};

Quoting from this SO Answer:

Passing the intial state to a component as a prop is an anti-pattern
because the getInitialState (in our case the constuctor) method is only called the first time the
component renders. Never more. Meaning that, if you re-render that
component passing a different value as a prop, the component
will not react accordingly, because the component will keep the state
from the first time it was rendered. It’s very error prone.

So if you can’t avoid such a situation the ideal solution is to use the method componentWillReceiveProps to listen for new props.

Adding the below code to your child component will solve your problem with Child component re-rendering.

componentWillReceiveProps(nextProps) {
  this.setState({ data: nextProps.data });  
}

The second issue is with the fetch.

_makeApiCall(endpoint) {
  fetch(endpoint)
    .then((response) => response.json())   // ----> you missed this part
    .then((response) => this.setState({ response }));
}

And here is a working fiddle: https://jsfiddle.net/o8b04mLy/

Leave a Comment