How to use APIs with React Functional Components
Tags: react, javascript, codenewbie, webdev
Published: 2021-08-27 17:14:02

<!-- wp:paragraph -->
<p>Using APIs in your react project is a common use case. In this tutorial, we will be looking at two use cases</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Loading API Data in the Background</li><li>Loading API Data on button click</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>We will be using functional components and the useEffect hook. Some familiarity is expected.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Loading API Data in the background</h2>
<!-- /wp:heading -->

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hcxag8j48b7u3r998bvv.gif" alt="React APP with API Data being loaded"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>In this use case, the data is only loaded once - whenever the user views the app or refreshes the page. Initially, a 'Loading…' text is shown. This text is later updated with the actual API data. Below is the code snippet of the component which causes the above behavior</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>{% gist https://gist.github.com/rahulbanerjee26/df0c1ca9dfbaf4bb195798965a5abb0e %}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's discuss the code in 3 parts, the states, the useEffect hooks, and the rendering logic</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>The states</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="javascript" class="language-javascript">const [isLoading, setIsLoading] = 
React.useState(true);</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We have two states. The <strong>isLoading</strong> state is a boolean variable initialized to True. This state is used to keep a track of whether the data is still loading or it has already been loaded. The <strong>setIsLoading</strong> function is used to toggle this state variable. After the API returns the data, we will use this function to toggle the value for <strong>isLoading</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="javascript" class="language-javascript">const [data, setData] = React.useState([]);</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Next, we have the <strong>data</strong> state. This state is initialized to an empty array. It will be used to store the data returned by the API. You can initialize the state to an empty object as well. However, the API I am using in the example returns a list and therefore an empty list seems like the right choice. The <strong>setData</strong> function is used to update the state variable <strong>data</strong> after the API returns the data.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>The useEffect Hooks</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="javascript" class="language-javascript">  React.useEffect(() =&gt; {
    const url = "https://randomuser.me/api/?results=15";
    fetch(url)
      .then((response) =&gt; response.json())
      .then((json) =&gt; setData(json['results']))
      .catch((error) =&gt; console.log(error));
  }, []);</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The above useEffect Hook is used to make the request to the API. The '[]' parameter tells React to run this hook only once. The hook runs after the page has loaded. A simple fetch request is made and after the promise(s) are resolved, we use the <strong>setData</strong> function to update the state variable <strong>data</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="javascript" class="language-javascript">  React.useEffect(() =&gt; {
    if (data.length !== 0) {
      setIsLoading(false);
    }
    console.log(data);
  }, [data]);</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The next useEffect hook runs whenever the state variable <strong>data</strong> is updated. It does a simple check, if the state variable <strong>data</strong> is not empty, i.e the API has returned the data, it sets the state variable <strong>isLoading</strong> to False.</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>Note: The above case assumes a happy case, i.e the API will always return the data. However, this is not true. Therefore error handling should also be added.</p></blockquote>
<!-- /wp:quote -->

<!-- wp:heading {"level":3} -->
<h3>The rendering logic</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="javascript" class="language-javascript">  return (
    &lt;div&gt;
      {isLoading ? (
        &lt;h1&gt;Loading...&lt;/h1&gt;
      ) : (
        data.map((user) =&gt; (
          &lt;h1&gt;
            {user.name.first} {user.name.last}
          &lt;/h1&gt;
        ))
      )}
    &lt;/div&gt;
  );
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The rendering logic is pretty straightforward, if the state variable 'isLoading' is True, we will display the 'Loading…' indication. If it is false, we simply map over the state variable 'data' and display all the items in the array.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Loading API data on button click</h2>
<!-- /wp:heading -->

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7wv20yfq1361fyw7b2h5.gif" alt="React load API on button Click"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Below is the entire code snippet</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>{% gist https://gist.github.com/rahulbanerjee26/ea4cb23e097fa079caa229e9319c6659 %}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We will discuss the code in 3 parts.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>States</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="javascript" class="language-javascript"> const [showData, setShowData] = 
React.useState(false);</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The first two state variables are the same as the ones in the previous section. We will discuss the third state variable <strong>showData</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>When the user views the page for the first time, we do not want them to see the API data or the 'Loading……' text. Therefore we add a simple check to see if the user has clicked the button. After the user clicks the button once, there are only two views</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>The 'Loading…..' text</li><li>The API Data</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Every time the user clicks the button again, we just toggle between the two views mentioned above.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Handle Click Function</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="javascript" class="language-javascript">  const handleClick = () =&gt; {
    setisLoadingData(true);
    setShowData(true)
    const url = "https://randomuser.me/api/?results=15";
    fetch(url)
      .then((response) =&gt; response.json())
      .then((json) =&gt; {
        setisLoadingData(false);
        setData(json["results"])
        console.log(data);
      })
      .catch((error) =&gt; console.log(error));
  };</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>This is similar to the first useEffect Hook in the first use case. The only difference is that we set our state variable <strong>showData</strong> to True.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Rendering logic</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code lang="javascript" class="language-javascript">return (
    &lt;div&gt;
      &lt;button onClick={handleClick}&gt; Load Data &lt;/button&gt;
      {showData ? (
        isLoadingData ? (
          &lt;h1&gt;LOADING DATA........&lt;/h1&gt;
        ) : (
          data.map((user) =&gt; (
            &lt;h1&gt;
              {user.name.first} {user.name.last}
            &lt;/h1&gt;
          ))
        )
      ) : (
        &lt;div&gt;&lt;/div&gt;
      )}
    &lt;/div&gt;
  );</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>First, we have a check for showData, this is to ensure that initially, the user doesn't see the 'Loading….' text nor the API data. After the user clicks the button, showData is set to True. After this, the rendering logic is similar to the first use case.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I hope you found this article helpful. Add me on <a href="https://www.linkedin.com/in/rahulbanerjee2699/">LinkedIn</a>, <a href="https://twitter.com/rahulbanerjee99">Twitter</a></p>
<!-- /wp:paragraph -->