33
Fetching Data in React
This blog post will teach you how to fetch data from an external API and use it in your React apps.
Before you start reading you should be familiar with React, useState and useEffect hooks in React.
We will look at the following ways to fetch data:
- Using Fetch API
- Using async function
- Using Axios
- Using custom hooks
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It provides a global fetch( ) method that provides an easy, logical way to fetch resources asynchronously across the network.
We will use the fetch( ) method which takes a single argument i.e the path you want to fetch data from and it returns a promise containing a response.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
The async function returns a promise and the await keyword makes the function wait for a response.
Here's how we can use async/await to fetch data
async function fetchData() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos/3"
);
const data = await response.json();
console.log(data);
Axios is a library that is used to fetch data and it already gives the result in JSON, so we don't have to convert it.
First, we have to install Axios with the following command:
npm install axios
To use axios in our project we have to import it into our project
import axios from "axios"
React.useEffect(() => {
axios.get("https://jsonplaceholder.typicode.com/todos/3")
.then((response) => (console.log(response));
}, []);
Here we used the .get() method to make a get request to our endpoint.
We will make our custom react hook to fetch data which will take a single argument that is the endpoint we want to fetch the data from.
import { useEffect } from "react";
const useFetch = (url) => {
useEffect(() => {
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
}, []);
};
export default useFetch;
33