Axios
What is Axios?
• It is a library which is used to make requests to an API, return data from the API, and
then do things with that data in our React application.
• Axios is a very popular (over 78k stars on Github) HTTP client, which allows us to
make HTTP requests from the browser.
Syntax:
const getPostsData = () => {
axios
.get("API URL")
.then(data => [Link]([Link]))
.catch(error => [Link](error));
};
getPostsData();
Installing Axios
• In order to use Axios with React, we need to install Axios. It does not come as a
native JavaScript API, so that's why we have to manually import into our project.
• Open up a new terminal window, move to your project’s root directory, and run any
of the following commands to add Axios to your project.
Using npm:
$ npm install axios
To perform this request when the component mounts, you use the useEffect hook. This
involves importing Axios, using the .get() method to make a GET request to your endpoint,
and using a .then() callback to get back all of the response data.
What if there's an error while making a request? For example, you might pass along the
wrong data, make a request to the wrong endpoint, or have a network error.
In this case, instead of executing the .then() callback, Axios will throw an error and run
the .catch() callback function. In this function, we are taking the error data and putting it in
state to alert our user about the error. So if we have an error, we will display that error
message.
Program: create a react program to generate random joke using API.
[Link]
import React,{ useState,useEffect } from 'react'
import axios from "axios";
const Randomjokeapi = () =>
{
const[joke,setJoke]=useState("");
const fetchJoke=()=>
{
axios
.get("[Link]
.then((response)=>
{
const{setup,punchline}=[Link];
setJoke(`${setup} ${punchline}`);
})
.catch((error)=>{
[Link](error);
});
};
useEffect(()=>
{
fetchJoke();
},[]);
return
(
<div>
{joke}
<button onClick={fetchJoke} >Generate Joke </button>
</div>
)
}
export default Randomjokeapi