React is a powerful JavaScript library for building user interfaces. It was
developed by Facebook and is widely used in web development to create dynamic and
interactive UIs.
In this tutorial, you will learn how to perform a GET request using Axios in React.js with Typescript code.
Full Source Code For Your Convenience
If you are a seasoned developer, you can copy and paste this full source code, and you can revisit this page later for a more specific step-by-step explanation.
Provided that you have installed Axios, of course. You can jump to the preparation section on how to install Axios in your project.
import React, { useState, useEffect } from 'react'; import axios, { AxiosResponse } from 'axios'; // Interface for modeling product data interface Product { id: number; title: string; price: string; category: string; description: string; image: string; } const App: React.FC = () => { const [data, setData] = useState<Product[]>([]); const url = 'https://fakestoreapi.com'; // Function to fetch data from the API const getProduct = async () => { try { const response: AxiosResponse<Product[]> = await axios.get(`${url}/products`); setData(response.data); } catch (error) { console.error('Error fetching data:', error); } }; // Call the getProduct function when the component mounts useEffect(() => { getProduct(); }, []); return ( <div> <h1>Products</h1> {data.map((item) => ( <div key={item.id}> <h3>{item.title}</h3> <p>Price: ${item.price}</p> <p>Category: {item.category}</p> <p>Description: {item.description}</p> <img src={item.image} alt={item.title} /> </div> ))} </div> ); }; export default App;
Prepare Typescript React Project
To create a React project with TypeScript, I am using a tool called Vite.
yarn create vite my-app --template react-ts
Axios is a promise-based HTTP client that allows developers to make HTTP requests
to a server.
To install the Axios library, use the following command:
yarn add axios
Perform GET Request
Implement the Axios GET method for HTTP requests. We are going to use
useState
for storing the data we fetch from the Fakestore API and
useEffect
for the lifecycle method that will run our function to fetch the data
with Axios.import { useState, useEffect } from 'react' import axios from 'axios'
Then, create an interface for modeling the data that we get from the API.
interface Product { id: number title: string price: string category: string description: string image: string }
Next, create a state for storing the data using
useState
.const App = () => { const [data, setData] = useState<Product[]>([]) return <div></div> } export default App
If you look at the
data
state, it contains a generic type of Product[]
,
which means the data
state accepts an array of Product
.Next, create an asynchronous function for calling the API with Axios like this.
let url = '<https://fakestoreapi.com>' const getProduct = async () => { try { const response = await axios.get<Product[]>(`${url}/products`) console.log('response getProduct', response.data) setData(response.data) } catch (error) { console.error('getProduct', error) } }
The Axios
get
method returns a response with a Product[]
type and updates
the data
state with the response data.Now, call the
getProduct()
function inside useEffect
, so the function is called
when the page is rendered for the first time.useEffect(() => { getProduct() }, [])
Here is the full source code:
import { useState, useEffect } from 'react' import axios from 'axios' interface Product { id: number title: string price: string category: string description: string image: string } const App = () => { const [data, setData] = useState<Product[]>([]) let url = '<https://fakestoreapi.com>' const getProduct = async () => { try { const response = await axios.get<Product[]>(`${url}/products`) console.log('response getProduct', response.data) setData(response.data) } catch (error) { console.error('getProduct', error) } } useEffect(() => { getProduct() }, []) return ( <div> {data.map((item) => { return <h3 key={item.id}>{item.title}</h3> })} </div> ) } export default App
Adding HTTP Headers
This is how to add HTTP headers to an Axios request. These headers can be used for
authentication or setting the content type of the request. You can customize the
headers as per your project's requirements.
Example Usage:
const getProductWithHeaders = async () => { try { const headers = { Authorization: `Bearer ${yourAccessToken}`, 'Content-Type': 'application/json', }; const response = await axios.get<Product[]>(`${url}/products`, { headers, }); console.log('response getProductWithHeaders', response.data); setData(response.data); } catch (error) { console.error('getProductWithHeaders', error); } };
Using Parameters in GET Requests
This is how to use parameters in an Axios GET request. This allows you to fetch
more specific data from the API, and the parameters can be customized based on your
needs.
Example Usage:
const getProductWithParameters = async (categoryId: number) => { try { const response = await axios.get<Product[]>(`${url}/products`, { params: { categoryId }, }); console.log('response getProductWithParameters', response.data); setData(response.data); } catch (error) { console.error('getProductWithParameters', error); } };
Using Query Parameters
This is how to send query parameters in a GET request using Axios. This provides flexibility to retrieve data from the API by filtering results based on
the sent parameters.
Example Usage:
const getProductWithQueryParams = async (queryParams: { param1: string, param2: string }) => { try { const response = await axios.get<Product[]>(`${url}/products`, { params: queryParams, }); console.log('response getProductWithQueryParams', response.data); setData(response.data); } catch (error) { console.error('getProductWithQueryParams', error); } };
Using Slugs in URLs
This is how to use slugs (dynamic parameters) in Axios URL requests. This is
useful when you need to fetch specific data based on a particular slug in the URL.
Example Usage:
const getProductWithSlug = async (slug: string) => { try { const response = await axios.get<Product[]>(`${url}/products/${slug}`); console.log('response getProductWithSlug', response.data); setData(response.data); } catch (error) { console.error('getProductWithSlug', error); } };
With this understanding, you can integrate Axios with React TypeScript to make custom HTTP requests for your project's needs.