Table of contents
What is Axios?
Axios is a promise-based HTTP library that allows you to make requests to a given endpoint,
An HTTP request endpoint is a targetable URL in the web application, such as https://localhost:3000/movies.
When you make a request, depending upon what kind of request you made, API performs operations accordingly. You can make GET, POST, PUT/PATCH, and DELETE requests.
Using Axios in React Project: Step-by-step guide
I will take an existing React project where we'll have to fetch some data about movies from TMDB (The Movie Database). And as of now, we'll just show the API object in the browser.
So we already have:
A React project setup.
An API key, which I got from here.
Step 1: Install Axios with npm/yarn -
npm install axios
Step 2: Create an Axios instance -
Axios lets you create custom instances for API requests. Each instance is a separate client that can carry its own configuration and options like base URLs, timeouts, and headers. Then, you can reuse the configuration for API calls using the same instance.
This is the axios.js file:
import axios from 'axios';
const instance = axios.create({
baseURL: "https://api.themoviedb.org/3",
})
export default instance;
Step 3: Create a file containing endpoints & API key -
This is Requests.js file:
const API_KEY = "de564tg67***********6";
const requests = {
fetchTrending: `/trending/all/week?api_key=${API_KEY}`,
fetchTopRated: `/movie/top_rated?api_key=${API_KEY}&language=en-US`,
fetchActionMovies: `/discover/api_key=${API_KEY}&with_genres=28`,
}
export default requests;
Step 4: Doing fetch operations in component file -
import React, { useEffect, useState } from 'react'
import axios from '../../axios';
import requests from '../../Requests';
function Component() {
const [movie, setMovie] = useState([]);
useEffect(() => { //fetch data
async function fetchData(){
const request = await axios.get(requests.fetchTrending);
setMovie(
request.data.results[1] // 1-> index
)
return request;
}
fetchData();
},[])
console.log(movie);
- here in this file, we are using useState hook to set the API data in the state variable movie, a useEffect hook which will execute the fetchData() function once the component gets mounted.
The request object gets data from fetchTrending endpoint using axios's GET request. setMovie function will set the data object lying at 1st index to movie state variable, and then we get the data object displayed in the browser -
Now you can use this object's data to inflate to your components :)
Thanks for reading!