Fetch API data using useEffect React Hook
Today we’ll show you how to fetch API data using useEffect React Hook. In the previous article, we have provided the examples of the useEffect React Hook.
Here, we will see how to place an API call using useEffect and get the data from the API on demand using React Hooks. Let’s take an example where we will use the button and input field to get a record by id via API. If the input field is empty then we will fetch all the records.
Fetch API data using useEffect
1. Create a react application
First, we will create a react application using the `create-react-app` package. Run the following command to create a react app.
npx create-react-app fetch-api-data-useeffect
2. Design a form
Let’s design a simple form to fetch the API data. We will use the input field and button whereas the button will be used to fetch the data by id. If the input field will be empty then we will fetch all the records. So we will change the button text conditionally based on the input value.
import { useState } from "react";
function App() {
const [inputId, setInputId] = useState('');
const [id, setId] = useState('');
// handle click evnet of the button
const handleButtonClick = () => {
setId(inputId);
}
return (
<div class="App">
<div class="form">
<h3>Fetch API data using useEffect - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3>
<input type="text" value={inputId} onchange="{e" ==""> setInputId(e.target.value)}
style={{ marginRight: 10 }} />
<input type="button" value="{inputId" ?="" 'fetch'="" :="" 'fetch="" all'}="" onclick={handleButtonClick}>
</div>
</div>
);
}
export default App;
3. Create an API to fetch data
Now, we’ll create an API to fetch data and call that API using useEffect React Hook. We’ll fetch all records on page load. For the demo purpose, we’ll use the JSONPlaceholder fake API.
import { useEffect, useState } from "react";
function App() {
...
const [posts, setPosts] = useState([]);
useEffect(() => {
let url = 'https://jsonplaceholder.typicode.com/posts';
if (id) {
url += `/${id}`;
}
fetch(url)
.then(res => res.json())
.then(res => {
setPosts(Array.isArray(res) ? res : [res]);
});
}, [id]);
...
...
return (
<div class="App">
<div class="form">
...
...
</div>
<ul>
{posts.map(x => <li>{`Id: ${x.id} | Title: ${x.title}`}</li>)}
</ul>
</div>
);
}
export default App;
Here, we have changed the API URL dynamically based on the `id` and also stored the response in the state variable in array format. We have passed the `id` as dependency parameter in the `useEffect` to conditionally run the code using useEffect.
4. Output
Let’s combine all code together and see how it works.
App.js
import { useEffect, useState } from "react";
function App() {
const [inputId, setInputId] = useState('');
const [id, setId] = useState('');
const [posts, setPosts] = useState([]);
useEffect(() => {
let url = 'https://jsonplaceholder.typicode.com/posts';
if (id) {
url += `/${id}`;
}
fetch(url)
.then(res => res.json())
.then(res => {
setPosts(Array.isArray(res) ? res : [res]);
});
}, [id]);
// handle click evnet of the button
const handleButtonClick = () => {
setId(inputId);
}
return (
<div class="App">
<div class="form">
<h3>Fetch API data using useEffect - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3>
<input type="text" value={inputId} onchange="{e" ==""> setInputId(e.target.value)}
style={{ marginRight: 10 }} />
<input type="button" value="{inputId" ?="" 'fetch'="" :="" 'fetch="" all'}="" onclick={handleButtonClick}>
</div>
<ul>
{posts.map(x => <li>{`Id: ${x.id} | Title: ${x.title}`}</li>)}
</ul>
</div>
);
}
export default App;
Run the application and check the output in the browser.
Output - Fetch API data using useEffect React Hook - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding..!!