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.
1 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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 className="App"> <div className="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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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 className="App"> <div className="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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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 className="App"> <div className="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.
That’s it for today.
Thank you for reading. Happy Coding..!!
sir , i m learn HTML, CSS, JS but react js very hard one. o i think u have one you tube channel plz one video for react course and also js or type script course .
First of all, I will suggest you to check the basic concept of the JS then start the basic learning of the react. Refer to the following link.
JavaScript for React
React Beginner