[React] How to make API calls in React.js

forhjy
Nov 14, 2020

--

With axios

Photo by Jesse Kao on Unsplash

fetch is often used to make API calls in javascript. Today, I will introduce making API calls using axios .

First, create new project and install axios with npm.

$ npx create-react-app apiTest
$ cd apiTest
$ npm add axios

API requests can be made using methods such as GET, PUT, POST, DELETE and etc by using axios.

Here’s how you use axios.

import axios from 'axios';
axios.get('/users/1');

And if you want to update new data, use axios.post() like below.

axios.post('/users', {
username: 'forhjy',
name: 'jy'
});

useEffect will make request when the component starts to render.

For the API, I will use API for practice from JSONPlaceholder.

The address is https://jsonplaceholder.typicode.com/users .

App.js

If you made your code to call API, start your react. And you will get the localhost page like below image.

$ npm start
Check your console!

--

--