In this article, we will understand how to make use of the useEffect hook in React to retrieve data from an API.

This article assumes that you have a general understanding of how to fetch/retrieve data from an API as well as the fundamentals of React and React Hooks.

 Install axios package 

Make sure the axis package added in package.json file under dependencies section
"dependencies": {
"axios": "^0.18.0",
},


Below are the steps to fetch data from API 

1. Import useState and useEffect

2. Create our posts variable as well as the setPosts function via useState

3. Create out useEffect function — this is where we'll perform our fetch

4. Within our useEffect function we'll use setPosts to set all posts that we received

5. Use posts.map to iterate all the posts to display in the browser


Fetch all posts from API using useEffect?

import React, { useState, useEffect } from 'react'
import axios from 'axios'

function DataFetching() {
const [posts, setPosts] = useState([])


useEffect(() => {
axios
.get(`https://jsonplaceholder.typicode.com/posts`)
.then(res => {
setPosts(res.data)
})
.catch(err => {
console.log(err)
})
}, [])


return (
<div>
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
)
}

export default DataFetching

Fetch single post title from API using useEffect?


import React, { useState, useEffect } from 'react'
import axios from 'axios'

function DataFetching() {
const [post, setPost] = useState({})
const [id, setId] = useState(1)
const [idFromButtonClick, setIdFromButtonClick] = useState(1)

useEffect(() => {
axios
.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
.then(res => {
console.log(res)
setPost(res.data)
})
.catch(err => {
console.log(err)
})
}, [idFromButtonClick])

const handleClick = () => {
setIdFromButtonClick(id)
}

return (
<div>
<input type="text" value={id} onChange={e => setId(e.target.value)} />
<button type="button" onClick={handleClick}>Fetch Post</button>
<div>{post.title}</div>
</div>
)
}

export default DataFetching