Photo by Ferenc Almasi on Unsplash

GET Requests in React

kevinMEH

--

Let’s start sending GET Requests in our React application!

There are several ways to send requests, but in this tutorial we’re going to be using a library called Axios. I’ll explain things as we progress, but if something doesn’t make sense or if you‘re curious about how something works, don’t be afraid to check the Axios documentation and find whatever it is you need.

In this project, we’re going to work with the following API endpoint:

https://api.bazaar.liao.gg/api/

We’re going to be building a mock e-commerce website where you pull products from the API above and then display the products for your user. Kinda like this one. (But not as complicated, I promise!) Let’s get started!

Getting Started

Before we get started, you must follow me on GitHub. Seriously. The tutorial will not work unless you follow me. (Ok fine, I’m lying. You don’t have to follow me, but it’s strongly recommended you do.)

Ok, now that you’ve followed me, let’s start by create a new React app. I’m going to be using Vite as my build tool.

If you already have a directory created for your project, navigate to the directory and type in this:

npm create vite@latest ./

This tells npm to create a new Vite app in the current directory. (Note the “./” argument!)

If you do not have a directory created, type in this:

npm create vite@latest

Follow the instructions on the screen. Use arrow keys to navigate the options. Remember to select React as our framework!

When your project is initialized, follow the instructions on screen and install all necessarily packages (npm install). Then, run npm run dev to start a development server.

Navigate to http://localhost:3000 and check if the page is there. If yes, congrats!

Optional Section: Using any build tool will result in some pre-generated boilerplate. Let’s clean it up! Delete App.css and logo.svg. Your project structure should look like this:

We’re going to be working in the App.jsx file (feel free to put it in another file, but for simplicity and demonstrational purposes, I’ll use App.jsx). Delete the boilerplate until you end up with something like this:

Nice! Now navigate back to http://localhost:3000/ and make sure you didn’t break anything. If you did, check the error message Vite gives you and try and fix it. Maybe you forgot to close a tag, or you’ve accidentally deleted a necessary file, etc.

Installing Axios

Now for the fun part! Install Axios with the following command:

npm install axios

Wait for the slow ass Brooklyn Tech wifi to finish installing, and then head on over to App.jsx.

At the top of the page, import axios with

import axios from "axios";

Lets also import useEffect, because we’re going to be using it to fetch the product when our App component is first mounted.

import { useEffect } from "react";

Then, in the body of our App() function, add the following pieces of code:

Oh yeah, do you see that arrow symbol? That’s a ligature my font uses, it’s just a fancy display of “=>”. I don’t know how to disable it lol… so you’ll have to deal with it for now.

Go back to http://localhost:3000/, reload the page, hit F12 to open the dev tools, and click on the console. If everything works correctly, you should see an array of 6 products in the console.

Did it work? If so, congrats! (If not, make sure that you’ve imported axios and that you’ve actually installed it before using it.) You’ve just sent your first API call from a React app. Let me explain what’s going on, starting from the top of the page.

When we import axios from “axios”, we’re importing the axios object, which contains a variety of helpful methods that we can use to send requests. Among which is the .get() method, which takes in a URL as a parameter (in this case, https://api.bazaar.liao.gg/api/products?page=1) and returns a Promise with the server’s response being the resolution value of the Promise.

Note: Not valid syntax or actual implementation, demonstrational purposes only.

The response that is resolved from the .get() method is an object that represents the response from the server. It has fields like config, headers, status, statusText, and other properties that tells us all about the response. But right now, we’re not interested in any of that other stuff. What we want is the data from the response, which we can access by using response.data.

We’re wrapping the axios.get() inside a useEffect() hook because we don’t want to resend the request every time we rerender the component. When we write useEffect(() => {}, []) with an empty array at the end, we’re telling React that we want the function inside the useEffect() to be executed only when the component is first mounted, and nowhere else.

So our program goes like this:

Mount the component. Then, send a request to https://api.bazaar.liao.gg/api/products?page=1, and when the response arrives, console.log the data field of the response.

Ok wait! Before you move on, one other thing I want to talk about:

Remember when I said that axios.get() is a function that takes in a URL as an argument? I was kinda lying. axios.get() also accepts a second parameter, a config object, where you can specify queries to send with the request instead of just embedding the queries into the URL itself. Take this for example:

Both lines of code do the same thing, which is sending a GET request to the base URL with a query “page” of 1. However, the second one is much easier to work with. Lets say that we want to have our user specify what page to GET and what filter to use. Compare the two functions below and pick which one you would rather use…

Since filter is a string of words and may contain spaces, we replace all of it’s spaces with “+” instead. Remember that spaces aren’t allowed in URLs!

The first one is clearly easier to work with. Lets go back to our useEffect() and fix our messy .get() method and replace the hardcoded queries with a query object instead.

Working With the Products API

In this tutorial, we’re going to be working with the API endpoint I specified above. Here it is again in case you forgot:

https://api.bazaar.liao.gg/

NOTE: Send requests sparingly. The server automatically rate limits and time out IP addresses who send too many requests in a short span of time, so beware. Do not spam the API.

The API above has 2 paths that you can use: /api/products and /api/product/xxxx. In this tutorial, we’re going to be working only with api/products.

(If you’re curious, /api/product/xxxx will give you the complete product information for a specific product xxxx, where xxxx is the product URL of the product that is stored in the database. You can find the product URL as a property of the product object, which we will explore later on.)

/api/products accepts 2 queries, page and filter. The page query specifies the specific page of products to be returned, and the filter query (if included) tells the server to return only products with names that contains the filter keyword. We’re not going to be working with filter, but I’m gonna explain it in case you want to add some searching functionality or whatever.

Oh yeah, and note: Each page of products contains 6 products, and there are a total of 14 products in the database. That means that the last product page that will return products is page 3 (and it will contain 2 products). If you go beyond page 3, you will get an empty array as a response.

Here are two examples of calls to the API.

https://api.bazaar.liao.gg/api/products?page=2

https://api.bazaar.liao.gg/api/products?page=1&filter=wood

(Yes, I know, the URL is very long and torturous to type, and I could probably shorten it if I wanted to. But I don’t get paid enough and I’m lazy, so you’ll have to deal with typing the whole URL out for now. Anyways.)

The first URL tells the server to give us the second page of products with no filters. The response should look a little something like this:

The second URL tells the server to give us the first page of products that contains the word “wood” in their names. The response should look a little something like this:

In fact, you can try out the API right now! Head on over to the URLs and you should see the responses in plain text.

NOTE: Send requests sparingly. The server automatically rate limits and time out IP addresses who send too many requests in a short span of time, so beware. Do not spam the API.

The API’s Response

https://api.bazaar.liao.gg/api/products will return an array of products as it’s response, its length ranging anywhere from 0 to 6 products. (If you get an array of 0 products, that means that there are no more products.)

Each product in the array is an object with properties name, thumbnail, price, and url. There’s also a description property stored on the database, but you can only get it by fetching from /api/product/product-url, so let’s not worry about it for now.

So, to console.log the names of every product in the response, we would write something like this:

Async arrow functions exist! Simply prefix the arrow function with the async keyword, and congrats! It’s now an async arrow function, and you can use await in it.

Great! Now we know how to access all the products that have been returned from the products API. But how do we display our newly fetched products to our user?

We would need to use useState. Since our products are fetched AFTER the initial mount of the component, we need to store the products in our state and tell React when our products are received so it knows when to update our component.

Start by importing useState at the top of the file:

import { useState, useEffect } from "react";

Next, we’re going to create a new state called products. Inside the body of App.jsx, write

const [products, setProducts] = useState([]);

Since products is going to be an array, we’re going to initialize it into an empty array instead of null or whatever. That way, when we use array methods, we don’t get an error.

Inside the useEffect, add a statement that sets products once we receive the response from the server.

Finally, in our return statement, let’s use a .map() to map all the products into product cards, complete with their titles, images, and prices. Feel free to make a separate component for the card itself!

Your final page should look a little something like this:

Conclusion

Aaaaannnnnndddddd congrats! You’ve reached the end of the tutorial, and you now know how to send and process requests in your React application.

This series of tutorials serves only as a shallow exploration of APIs, requests, and integrating your frontend and your backend. In reality, there are so many more things you program your website to do on the web. I encourage you guys to go on and learn more about full stack programming, about servers and databases and handling POST requests and data processing and all that stuff.

Bye!

If you’re curious about the API and you’re wondering how it works, it’s open sourced, so go check it out! There’s some stuff missing from it that I’ve recently added, like rate limit protections and some reverse proxy stuff, but otherwise it’s mostly up to date.

If you’re curious about the website (Kevin’s Bazaar) I shared at the beginning and you’re wondering how I made it, it’s open sourced, so go check it out! Specifically, if you’re looking to see how I integrated the frontend and the backend, check out Data.jsx, Products.jsx, and ProductPage.jsx.

--

--