title: Handling promises with fetch() in React?
body: <p>I'm creating my first MERN stack application, and trying to implement a simple API that calls my express server from my React front-end components. I have the API working on the back end, and it is sending the data correctly through <code>fetch()</code>, but I'm having trouble resolving the promise from <code>fetch()</code> in my React component, with the call not stopping firing. My code looks as follows (assuming as of right now all API calls return a dummy format like <code>{ title: 'foo', ... }</code>:</p>
  
  <pre class="lang-js prettyprint-override"><code>import React, { useState } from 'react';
  import 'core-js/stable';
  import 'regenerator-runtime/runtime';
  
  const getApiData = async (route) =&gt; {
    try {
      let apiData = await fetch(route);
      let apiDataJson = await apiData.json();
      return apiDataJson;
    } catch (err) {
      throw new Error('Error on fetch', {
        error: err
      })
    }
  }
  
  var retrieve_data = async (route, setterCallback) =&gt; {
    await getApiData(`/api/${route}`).then((data) =&gt; {
      console.log('Data retrieved from API')
      setterCallback(&lt;div&gt;{data.title}&lt;/div&gt;)
    }).catch(() =&gt; {
      setterCallback(&lt;div&gt;ERROR&lt;/div&gt;)
    })
  }
  
  const MyComponent = () =&gt; {
  
    const [innerDiv, setinnerDiv] = useState(0);
  
    let data = retrieve_data('myEndpoint', setinnerDiv);
  
    return(
      &lt;div&gt;
        &lt;h1&gt;Data Retrieved in MyComponent:&lt;/h1&gt;
        {innerDiv}
      &lt;/div&gt;
    );
  } 
  </code></pre>
  
  <p>When I compile the above the component successfully renders (i.e. <code>&lt;MyComponent /&gt;</code> looks like:</p>
  
  <pre><code>&lt;div&gt;
      &lt;h1&gt;Data Retrieved in MyComponent:&lt;/h1&gt;
      &lt;div&gt;foo&lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>However, then <code>then</code> block keeps executing (i.e. the <code>'Data retrieved from API'</code> logs to the console hundreds of times/second until I close the application. How can I stop this from executing once it has set the component? Thanks!</p>