title: React setState inside componentDidUpdate causing infinite loop
body: <p>Can someone help me solve how do I setState inside <code>componentDidUpdate</code> and not have an infinite loop? Some suggestions said to have a conditional statement, but I am not too familiar with how do I set the conditional for my code.</p>
  
  <p>This is what my code looks like:</p>
  
  <p>I have a dashboard component that gets all the companies and projects data from external functions where the fetch happens and then updates the state. The projects are associated with the company's id.</p>
  
  <p>I am able to get the list of all the projects in JSON, but I can't figure out how to update my projects state inside componentDidUpdate once rendered.</p>
  
  <p><strong>CompanyDashboard.js</strong></p>
  
  <pre><code>import { getCompanys } from "../../actions/companyActions";
  import { getProjects } from "../../actions/projectActions";
  
  class CompanyDashboard extends Component {
    constructor(props) {
      super(props);
      this.state = {
        companies: [],
        projects: []
      };
    }
  
    componentWillMount() {
      // get all companies and update state
      getCompanys().then(companies =&gt; this.setState({ companies }));
    }
  
    componentDidUpdate(prevState) {
      this.setState({ projects: this.state.projects });
    }
  
    render() {
      const { companies, projects } = this.state;
      {
        companies.map(company =&gt; {
          // get all the projects
          return getProjects(company);
        });
      }
      return &lt;div /&gt;;
    }
  }
  
  export default CompanyDashboard;
  </code></pre>
  
  <p><strong>companyActions.js</strong></p>
  
  <pre><code>import { getUser, getUserToken } from './cognitoActions';
  import config from '../../config';
  
  export function getCompanys() {
      let url = config.base_url + '/companys';
      return fetch(url, {
        method: 'GET',
        headers: {'token': getUserToken() }
      })
      .then(res =&gt; res.json())
      .then(data =&gt; { return data })
      .catch(err =&gt; console.log(err));
  }
  </code></pre>
  
  <p><strong>projectActions.js</strong></p>
  
  <pre><code>import { getUserToken } from './cognitoActions';
  import config from '../../config';
  
  export function getProjects(company) {
    let url = config.base_url + `/companys/${company._id['$oid']}/projects`;
    return fetch(url, {
      method: 'GET',
      headers: {'token': getUserToken() }
    })
    .then(res =&gt; res.json())
    .then(data =&gt; { return data })
    .catch(err =&gt; console.log(err));
  }
  </code></pre>