Search code examples
javascriptreactjslifecycle-hook

componentDidUpdate() working mostly, but not rendering new data


I am using the componentDidUpdate() method and for the most part, it is doing what it should. It runs the function to get the data from the API as well as logs it to the console. The problem is that it does not render the new data on the front end. The only time it renders the new data is if the component actually mounts (if the page is refreshed). I feel like I'm very close, but have hit a dead end. Here is my code:

import React from 'react';
import Nav from './Nav';

class List extends React.Component {
constructor(props) {
super(props);
this.state = {
  APIData: []
}
}

getAPIData() {
const url = `http://localhost:3001${this.props.location.pathname}`;
return fetch(url, {
  method: 'GET',
  mode: 'CORS',
  headers: {
    'Accept': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
    return data;
  }).catch(err => { console.log('Error: ', err) });
};

dataList() {
return (
  <div>
  {this.state.APIData.map((APIData) => (
    <p> And the data returned is -> {APIData.firstName} 
{APIData.lastName} !</p>
  )
  )}
  </div>
) 
}

componentDidMount() {
console.log(this.props.location.pathname);

this.getAPIData()
  .then(data => {
    console.log('in List.js ', data);
    this.setState({
      APIData: data
    });
  });
}

componentDidUpdate(prevProps, prevState) {
console.log(this.props.location.pathname);
// only update if the data has changed
this.getAPIData()
.then(data => {
  if (prevProps.data !== this.props.data) {
    this.setState({
      APIData: data
    });
  }
  console.log(data);
});
}

render() {
return (
  <div>
    <Nav />
    <br />
    <br />
    <br />
    <br />
    <div>
      {/* {this.state.APIData.map((APIData) => (
        <p> And the data returned is -> {APIData.firstName} 
 {APIData.lastName} !</p>
      )
      )} */}
      {this.dataList()}

    </div>

  </div>
 );
 }
 }



 export default List;

Solution

  • I think it may be this block:

    if (prevProps.data !== this.props.data) {
      this.setState({
        APIData: data
      });
    }
    

    Are you actually passing a data prop to this component?

    If not, then it would be checking if undefined !== undefined and never executing.

    If you are, then you might check if the data reference is actually changing, or you're just mutating the inside of the object.