Fetch data using API in React
In this course for the data, we have used is the API endpoint from http://jsonplaceholder.typicode.com/users
For this lesson we will show some simple ways to fetch data from using an API.
Fetch method
The fetch() is a method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.
Write following code in App.js and run.
import './App.css';
import { useEffect } from "react";
function App() {
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(json => console.log(json))
}, []);
return (
<div>
<h1>Different ways to fetch Data</h1>
</div>
);
}
export default App;
useEffect(): A hook that would runs on the first render and at any time that any dependency value changes.
To run the application open terminal then type command npm start
Output: Data we fetched would be print out in the console.
Axios Package
Axios is a promise-based HTTP client designed for Node.js and browsers. so, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations (CRUD). It is an open-source collaboration project hosted on Github. It can be imported in plain Javascript or with any library accordingly.
Promise-based: Programming paradigm that uses promise object to handle asynchronous operation.
To install Axios open terminal and write the following command.
npm i axios
Then write following code in App.js and run.
import { useEffect } from "react";
import axios from "axios"
function App() {
useEffect(() => {
axios.get("https://jsonplaceholder.typicode.com/todos")
.then((response) => console.log(response.data));
}, []);
return (
<div>
<h1>Different ways to fetch Data</h1>
</div>
);
}
export default App;
To run the application open terminal then type command npm start
Output: Data we fetched would be print out in the console.