How to fatch data from an api with simple step.
This short tutorial will guide you through the simple steps of using the Fetch API for external data fetching within your React application.
Let’s get started …
Step 1: Create a new React application
The very first step is to create a new React application. The easiest way to do so is to use the create-react-app scaffolding script which can be executed with the following command:
$ npx create-react-app fetch-app
Step 2: Select a data source
Next, we need an external data source which we can use to retrieve data from. I service which is free to use and is offering multiple endpoints which JSON formatted test data is mockbee which is available at https://mockbee.netlify.app/docs/api/apps/e-commerce
1. GET /api/products#
Request URL: /api/products
HTTP Method: GET
Response Body:
{
data: {
products: Array;
}
}
Functionality: This API call gets all products from the db.
Step 3: Next add the following import statement on top in .js
import React, { useEffect, useState } from “react”
By using this import statement we’re making sure that we’re able to make use of React’s useEffect and useState hook.
Inside App function introduces a new users component state which will later on hold our retrieved user sample data by using the useState hook:
const [productData, setProductData] = useState([])
Next add a function fetchUserData which uses the Fetch API to retrieve data from the users endpoint of the mockbee service:
const [productData, setProductData] = useState([])
const productsApiurl = "/api/products";
useEffect(() => {
getData(productsApiurl, setProductData)
}, []);
console.log(productData);
If the data is retrieved successfully we’re calling setproductData function in order to set the component user state to the data which was retrieved.
Step 4: Output fetched data
Finally we need to show the retrieved data to the user. Change the return statement of App component to what you can see in the following code listing:
const [productData, setProductData] = useState([]);
const productsApiurl = "/api/products";
useEffect(() => {
getData(productsApiurl, setProductData)
}, []);
{productData.products?.map((item) => {
return <WatchCard key={item.id} item={item} />;
})}
Subscribe to my newsletter
Read articles from Shah Alam Tyagi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by