How do I Display Data from an API in React

Overview:

I am trying to use React to display data from an API. I have the “building blocks” of what I need, but I am trying to figure out how to combine them.

Problem:

I have a page that gets Rendered, a fetch call that requests data from an API, and some code that loops through the returned object.

How do I combine these three things so that I can see the content rendered on the page?

Thanks!

Here is my React code:

import { ... } from "...";

const Index = () => (
  <Page>
    <Frame>
      // HERE IS WHERE I WANT TO LOOP THROUGH THE API RESULTS
    </Frame>
  </Page>
);

export default Index;

Here is how I fetch data from an API:

function getDataFromApi() {
  var url = "api.example.com";
  return fetch(url, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  })
  .then((response) => response.json())
  .then((responseData) => {
    return responseData;
  })
  .catch((error) => console.warn(error));
}

Here is how I’m looping through an object:

var i;

for (i = 0; i < objects.length; i++) { 
  var object = objects[i]
  console.log(object);
}

Answer

You need to call the endpoint when the component gets rendered, but only the first time, if additional renders happen you usually don’t want to keep calling the API.

import React, { useEffect } from "react";

const Index = () => {
  useEffect(() => {
    getDataFromApi() // <--- call your API on the first render only
  }, []);

  return (
  <Page>
    <Frame>
      // HERE IS WHERE I WANT TO LOOP THROUGH THE API RESULTS
    </Frame>
  </Page>
  );
}

export default Index;

The hook useEffect runs whenever one of the dependencies changes, in this case there are cero dependencies, therefore this hook will only run once! How do you know there are no dependencies?

useEffect(() => {
   // Your code
}, []); //<---- These are your dependencies, the array is empty, therefore no dependencies for this hook.

The second thing is to store the API response somewhere, we usually use the local state, but you can use a library such as redux, mobox, or something else to store the data, in this example I’m going to use the local state.

import React, { useState, useEffect } from "react";

const Index = () => {
  const [data, setData] = useState([]); // <--- Initialize the state with an empty array
  useEffect(() => {
    getDataFromApi()
      .then((response) => setData(response)); // <---- Set the data to the local state
  }, []);

  return (
  <Page>
    <Frame>
      // HERE IS WHERE I WANT TO LOOP THROUGH THE API RESULTS
    </Frame>
  </Page>
  );
}

First you need to initialize the local state by using the useState hook. The, after the server response you need to set the response to the local state so you can use it on your component.

return (
  <Page>
    <Frame>
      { data.map((item) =>
         <p key={item.id}>{item.name}</p>
       )}
    </Frame>
  </Page>
  );

Given that data is an array, whenever the API responds the data gets assigned to the local state and then using map you can loop the array and render a paragraph or any other component for each item.

You need to make sure to set a key to each element in the loop, this tells react to mount/unmount component if the key changes, among other things.

Good luck!