OneCompiler

GET request in React using axios

410


Axios is a popular library to send API requests.
In this post you will know how to send a basic GET request to an API

Installing axios

To install axios Run below command

yarn add axios

Sending a GET request

For sendind the API Request we will be using a Fake online REST API
It has a set of 6 common resources

<img src="https://static.onecompiler.com/images/posts/3w3auaynz/api.png" alt="img" />

To get the posts,
we use code like below

import Axios from 'axios';
import React, { useState, useEffect } from 'react';

const App = () => {
	const [data, setData] = useState([]);
	useEffect(() => {
	Axios.get('https://jsonplaceholder.typicode.com/posts')
		.then( res => console.log(res.data))
		.catch( err => console.log(err) )
	},[])
	
	return (
		<div>
		Hey
		</div>
	)
}

The console will look like

<img src="https://static.onecompiler.com/images/posts/3w3auaynz/Annotation%202020-08-09%20162107.png" />

That's it guys, data contains all the info that is returned from the API