paint-brush
How to Fetch Data from APIs Using useEffect React Hookby@muhammadhasan
967 reads
967 reads

How to Fetch Data from APIs Using useEffect React Hook

by Muhammad HasanOctober 13th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this article, we will take a look at useEffect React hook to fetch data from an API. We will create a sample React application to pull data from the provider and use it in our application. In useEffect, we are loading data from JSONPlaceholder using fetch with async-await. We used this as an external API call and needs to be loaded asynchronously. Once the data is loaded it is setting it through setTodo.js. We are using Todos data provided by the provider.
featured image - How to Fetch Data from APIs Using useEffect React Hook
Muhammad Hasan HackerNoon profile picture

In this article, we will take a look at useEffect React hook to fetch data from an API. We will create a sample React application to pull data from the provider and use it in our application.

Setting up a basic React app

Let’s create a new React application using the following command:

npx create-react-app react-useeffect-demo

Open the application in the code editor:

Modify the App.js below:

Start the application using the following command:

yarn start

Once the application starts, the following screen will be displayed in the browser:

Setting up API data for our application

In order to fetch API data, we will be using Todos data provided by JSONPlaceholder.

Building the Application

In this section, we will be building the application. At first, we will enhance the App.js to fetch data from JSONPlaceholder and then we will write a small Todo component to display each todo.

Fetching data from the API

In order to fetch data, We have to enhanced App.js:

In App.js, our initial state is an empty array of todo. In useEffect, we are loading data from JSONPlaceholder using fetch with async-await. We used async-await as this an external API call and needs to be loaded asynchronously. Once the data is loaded, we are setting it through setTodo.

Todo.js:

Output:

I hope you enjoyed this post. Please share it.