Introduction
In the
previous article, we have learned about how to call useEffect only once and how to perform the cleanup. Now, in this article, we are going to learn about fetching data from API.
Data Fetching using useEffect() hooks
As we have already learned about the Axios library in previous article sections, in this article, for getting the data using useEffect() hook, we will use the same library.
So, to start using Axios library, we first need to install using the below command
After successful installation of the Axios library, it will be added to the node_modules folder.
Fetch Data from API using useEffect()
Here, we will use the Axios library to fetch data from API ‘
https://reqres.in/’. This is the same API we use in our previous article to fetch data.
Let’s look at the demo. Create a new functional component named DataList.js.
- import React,{useState,useEffect} from 'react'
- import axios from 'axios'
-
- function DataList() {
-
- const[users,setUsers] = useState([])
-
- useEffect(()=>{
- axios.get("https://reqres.in/api/users")
- .then(res=>{
- console.log(res)
- })
- .catch(err=>{
- console.log(err)
- })
- })
- return (
- <div>
- <ul>
- {
- users.map(user=> <li key={user.id}>{user.email}</li>)
- }
-
- </ul>
- </div>
- )
- }
-
- export default DataList
And, import the same in App.js. The output will be displayed as below.
Now, in the console, we can see that there is a warning that “setUsers() is assigned a value but never used” so, will now update the method in the useEffect() method. Now, the method will look like below.
- useEffect(()=>{
- axios.get("https://reqres.in/api/users")
- .then(res=>{
- console.log(res)
- setUsers(res.data)
- })
- .catch(err=>{
- console.log(err)
- })
- })
Now, run your application. It will be displayed as below.
As you can see, there are only 6 records but the console is getting an infinite loop. So, as we learned in the previous article, here, we are just fetching the records from API so this operation needs to be performed only once so adding an empty array as the second parameter in the useEffect() function.
- useEffect(() => {
- axios.get("https://reqres.in/api/users")
- .then(res => {
- console.log(res)
- setUsers(res.data.data)
- })
- .catch(err => {
- console.log(err)
- })
- },[])
Now, the output will be like below.
useEffect() is called only once when the component is mounted.
Now, we will go in details of how to fetch the data based on user input. In this example, we will be using https://jsonplaceholder.typicode.com/, as the previous API has limited API calls.
Add an input textbox that will take email address and fetch data accordingly.
- import React, { useState, useEffect } from 'react'
- import axios from 'axios'
-
- function DataList() {
-
- const [user, setUser] = useState({})
- const[id,setId] = useState(1)
-
- useEffect(() => {
- axios.get(`https:
- .then(res => {
- console.log(res)
- setUser(res.data)
- })
- .catch(err => {
- console.log(err)
- })
- })
-
- return (
- <div>
- <input type="text" value={id} onChange={e=>setId(e.target.value
- )}/>
- <div>{user.title}</div>
- </div>
- )
- }
-
- export default DataList
Now, the output will be displayed as below.
As we see in the console, there is a warning that we have specified an empty array but now in current, we need to call useEffect() whenever there is an update in id.
- useEffect(() => {
- axios.get(`https:
- .then(res => {
- console.log(res)
- setUser(res.data)
- })
- .catch(err => {
- console.log(err)
- })
- },[id])
Now, check that the output it is running as below.
Now, let’s add a button control, on click of which, the data should be displayed.
- import React, { useState, useEffect } from 'react'
- import axios from 'axios'
-
- function DataList() {
-
- const [user, setUser] = useState({})
- const [id,setId] = useState(1)
- const [idOnClick,setIdOnClick] = useState(1)
-
- const onClick = () => {
- setIdOnClick(id)
- }
- useEffect(() => {
- axios.get(`https:
- .then(res => {
- console.log(res)
- setUser(res.data)
- })
- .catch(err => {
- console.log(err)
- })
- },[idOnClick])
-
- return (
- <div>
- <input type="text" value={id} onChange={e=>setId(e.target.value)}/>
- <button type="submit" onClick={onClick}>Get Data</button>
- <div>{user.title}</div>
- </div>
- )
- }
-
- export default DataList
Now, the output will be displayed as below.
Initially, it will display the data with id 1.
Later, on click of the button, the data will be updated.
FAQs related to useEffect()
Q1: What is the purpose of useEffect() hook?
The hook is used to tell React that after render method is called component needs to perform some action, it will include either fetching of data or updating DOM and so on.
Q2: Why is useEffect() hook called inside a component?
The main purpose of calling hooks inside component is because it can easily access props and state declared inside component without the help of additional API to use it.
Q3: Is useEffect() called on every render?
The useEffect() hook can be called on every render, but it is not compulsory. It can be called only once by using an empty array as a second parameter or can be called based on an update of props or state. It depends on user requirement when to call it.
Summary
In this article, we have learned about getting from API using useEffect() hook in ReactJS.
You can download source code attached to this article. Now in the next article, we will learn about the next hook, i.e., useContext().