Hello everyone today i will show you how to fetch API in react js using 'useEffect'.
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
What does useEffect do?
By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API.
Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update.
Lets get dive into the code now-
First we will import the required modules
import React,{useState,useEffect} from 'react'
/*here we have imported the useState to change the state of the
data when the data gets update on the end point and useEffect
is used to fetch the data from the api
and it will run on every render
*/
Here we are fetching data from a fake api called jsonPlacenholder api which gives us data of a todo list with 'pending' and 'completed' status
const [todos, setTodos] = useState([]);
//useState is set to an empty arraya and later
//we will fetch the data from the end point
//and will store in the 'todos' array
useEffect -
useEffect(() => {
fetch('http://jsonplaceholder.typicode.com/todos')
.then(res => res.json())
.then((data) => {
setTodos(data)
console.log(todos)
})
}, [todos]);
- fetch is used to fetch the api from end point
- Then we set the state of todo to the data we have fetched from the API.
- In the last line of it [todos] is the dependency on which useEffect depends on.
Then we map the data using map function
{todos.map((todo) => (
<div className="card bg-dark text-light my-3">
<div className="card-body">
<h5 className="card-title">{todo.title}</h5>
<h6 className="card-subtitle mb-2 text-muted">
{ todo.completed &&
<span>
Completed
</span>
}
{ !todo.completed &&
<span>
Pending
</span>
}
</h6>
</div>
</div>
))}
Full source code -
import React,{useState,useEffect} from 'react'
import Fade from 'react-reveal/Fade'
import {Navbar,NavbarBrand,NavbarToggler,Nav,NavItem,NavLink,Collapse} from 'reactstrap';
import './App.css'
function App() {
const[toggle,setToggle] = useState(false);
const isToggle = () => setToggle(!toggle);
const [todos, setTodos] = useState([])
useEffect(() => {
fetch('http://jsonplaceholder.typicode.com/todos')
.then(res => res.json())
.then((data) => {
setTodos(data)
console.log(todos)
})
.catch(console.log)
}, [todos])
return (
<div className="">
<h1 className="text-primary text-center display-4 mb-5">React fetch api using useEffect</h1>
<div className="text-center" style={{display:"block",width:"50%",margin:"0 auto"}}>
<div style={{display:"flex",flexDirection:"column",justifyContent:"center",justifyItems:"center",width:"100%"}}>
{todos.map((todo) => (
<div className="card bg-dark text-light my-3">
<div className="card-body">
<h5 className="card-title">{todo.title}</h5>
<h6 className="card-subtitle mb-2 text-muted">
{ todo.completed &&
<span>
Completed
</span>
}
{ !todo.completed &&
<span>
Pending
</span>
}
</h6>
</div>
</div>
))}
</div>
</div>
</div>
)
}
export default App
Here is the Output-
I am newbie developer.So , if you find any mistake regarding any post Please highlight it
THANK YOU FOR READING THIS POST.
NOTE- In the example , we have bootstrap classes so , use bootstrap cdn or install and import it using npm or yarn package manager
Top comments (14)
That fetch is going to happen 2x at the start. The first time when todos is
[]
and then it will happen again when it's the result of the fetch as theuseEffect
deps will have changed. Then actually doesn't it just keep going because the object is different in todos?I am still learning so don't know much about in detail for now
I admire you on the fact that you are still learning but you still want to each others from what you have learned so far. That is a winning attitude right there. I wanted to help but LUKE already did.
Thanks for sharing.
Thank you
Great tutorial and setup. As others have pointed out you would want to leave out the dependency todos from your useEffect so that it doesn’t loop but overall you were thorough with your explanation and I believe you understand useEffect pretty well. Thank you for writing this article.
I am still at the learning stage and I even don't have 6-8 months of experience for now. So,kind of newbie here
We all start there and you are grasping concepts very well. Keep up the hard work and you will do fine. Posting articles like this and getting feedback will help as well. You are doing great. Keep pushing forward.
Thank you
I would say that if you only want it to run the first time your component loads you should leave the useEffects dependency empty but at my work we use exhaustive deps on the linter and it would throw an error for emptying the dependency array. Instead I would recommend putting the fetch in an if statement that checks todos.length === 0
Yes it will also work good
Thank you for this
I will try these things also
But when I leave it empty it throws error of empty dependency
Thanks mate
welcome buddy