Fetching and Displaying Data in React (Part 1)

Let’s create a Featured Products page using a shopping API

Adolf Schmuck
Better Programming

--

Code
Photo by Ferenc Almasi on Unsplash.

This article will focus on fetching data from an API and displaying it in the browser. This will be done using React Hooks. To keep things simple, we will be using a shopping API that I created for this article. However, the steps laid out here can be applied when fetching and displaying data from any API, whether it be a third-party API like the OMDb API or your own.

Let’s take a look at what we will set out to achieve. Imagine that we have a website with a Featured Products page where we want to display our top products. The items that are displayed on the page come from our shopping API. So in the end, what we want to create is a Featured Products page showing the products fetched from this API:

Featured Products page
Featured Products page

Getting Started

This article assumes that you already have a React app created. If you do not, simply run npx create-react-app my-app in the terminal (replacing my-app with the name of your app) to create the React starter package. You’ll know your React app has been successfully created when you see the words “Happy hacking!” in the terminal.

We’re going to be making our Get requests using Axios, so let’s go ahead and install that now as well:

npm i axios

Once that’s done, run npm start to start your React app. You should see this:

Starting your React app
Create React App

Let’s begin by creating a new file called FeaturedProducts.js. We’ll keep things simple here and just create this file in the src folder. And inside FeaturedProducts.js, we’ll start with a very basic functional component with just an h1 for now:

Let’s now import this in our App.js file, where we can go ahead and also remove the logo and most of the starter code. Our App.js file should look like this:

And if we look in the browser, we should see our h1:

Basic Featured Products page
Basic Featured Products page

Fetching Data From the API

As mentioned above, we will be using a simple shopping API that I created. The data includes six different items, along with their prices, images, descriptions, etc. Feel free to use it to follow along.

Shopping API
Shopping API

We’re going to be using the useState and useEffect Hooks, so let’s start by importing those in FeaturedProducts.js. Next, we need to create a state variable (which we’ll call products) and a function that updates it (which we’ll call setProducts). Since the data we’ll be fetching is essentially one big array, products will initially be set to an empty array:

Next, we’ll use Axios to fetch the data from the URL endpoint, so let’s go ahead and import Axios. And we’ll create a function for this called fetchProducts. So here, we’ll do axios.get(), which accepts our URL endpoint (https://shoppingapiacme.herokuapp.com/shopping). That is the URL for our shopping API. The Get request returns a promise. Then, inside the then block, we’ll log the response. And if there’s an error, we’ll log it in the catch block:

Now that we’ve created our fetchProducts function, we’ll use useEffect to call it. Since the useEffect Hook always gets called on the first render, we need to put our fetchProducts function inside useEffect so that it gets called when the page loads. Otherwise, our function will not get called and our data will not be fetched. So now when our page loads, our data will be fetched.

To prevent the useEffect Hook from being executed in an endless loop (due to the fact that it runs after every render and every update by default), we pass an empty array as a second argument to useEffect. By doing this, our useEffect Hook will run only after the first render — even if the component’s state is updated:

If we take a look in the console, we can see that we have successfully fetched the data from our API:

Data fetched from API
Data fetched from API

In order to display this data, we need to pass in this data to our setProducts function so that we can set our state to the data. As you can see in the console, we need to use data (highlighted in the screenshot) to access this data. So let’s go ahead and add setProducts(res.data) to our fetchProducts function inside the then block:

Displaying the Data

Now that we’ve fetched our data, we’re ready to display it on the page. So down in our return, let’s create a div for our products. And we’ll give it a className of item-container (we’ll be adding some basic styles just so that we can have something a little more interesting to look at). Now, we’ll take our products (our fetched data), map through them, and call each item product (the name we will use for each item when we render the specific properties we want to render). Then, we’ll put each of these products in a card div with a className of card, which we will use to create some very simple cards:

Let’s go ahead and add our styles now. We can just get rid of everything in App.css and add our styles in there. We’ll also center our h1 (as for img, we’ll get to this soon):

Now, all that we need to do is to get our data displayed on the screen. If we look at one of the items in the console, we can see that we have access to the the brand, color, description, id, image, item, and price:

Data fetched from API
Data fetched from API

For our cards, let’s display the item, brand, and image. To render these, we simply write product (the name we chose above for each item) and then whatever it is that we want to display (e.g. product.item):

And there we go. We now have our products displayed on the page:

Displaying the fetched data
Displaying the fetched data

You’ll notice, however, that we get a warning in the console: “Each child in a list should have a unique ‘key’ prop.” If we look at the React documentation, we see that a “key” is “a special string attribute you need to include when creating lists of elements.”

“Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.”

Missing Key warning
Missing Key warning

To fix our Missing Key issue, we’ll assign a key to our main card div. Most often, the ID from the data is used as the key, so that’s what we’ll use here. If the rendered items do not have stable IDs, the item index may be used as a last resort, though it is not recommended. For more information, refer to React’s documentation on lists and keys.

Now, the error is gone:

No more warning
No more warning

When we close the console, we can see our Featured Products page with our products:

Featured Products page
Featured Products page

Conclusion

So there we go. We’ve fetched the data from our API using React Hooks and Axios and displayed it on the screen. In Part 2, we will continue with the data we have here and set up dynamic routing so that we can display each item dynamically on its own page. Stay tuned.

Final Code

Final code for FeaturedProducts.js:

Final code for App.js:

Final code for App.css:

--

--