Skip to content
react

React fetch data from API and display in a table

Nov 24, 2022Abhishek EH2 Min Read
React fetch data from API and display in a table

We will make use of jsonplaceholder for our APIs.

Project setup

Create a react app using the following command:

1npx create-react-app react-fetch-data-table

Add the following styles in index.css:

index.css
1body {
2 margin-top: 20px;
3 display: flex;
4 justify-content: center;
5}

Calling the API

We will use the browser fetch API inside the useEffect hook to call the API to fetch data.

App.js
1import { useEffect, useState } from "react"
2
3function App() {
4 const [users, setUsers] = useState([])
5 const [loading, setLoading] = useState(false)
6 useEffect(() => {
7 setLoading(true)
8 fetch("https://jsonplaceholder.typicode.com/users")
9 .then(response => response.json())
10 .then(json => setUsers(json))
11 .finally(() => {
12 setLoading(false)
13 })
14 }, [])
15
16 return <div className="App"></div>
17}
18
19export default App

Here we are calling the API and setting the response to the users state. We also have a state named loading to display a loading text when the data is being fetched.

Displaying the data

In the code below, we are looping the users' array using map and displaying the user details in a table

App.js
1import { useEffect, useState } from "react"
2
3function App() {
4 const [users, setUsers] = useState([])
5 const [loading, setLoading] = useState(false)
6 useEffect(() => {
7 setLoading(true)
8 fetch("https://jsonplaceholder.typicode.com/users")
9 .then(response => response.json())
10 .then(json => setUsers(json))
11 .finally(() => {
12 setLoading(false)
13 })
14 }, [])
15
16 return (
17 <div className="App">
18 {loading ? (
19 <div>Loading...</div>
20 ) : (
21 <>
22 <h1>Users</h1>
23 <table border={1}>
24 <tr>
25 <th>Name</th>
26 <th>Email</th>
27 <th>Phone</th>
28 </tr>
29 {users.map(user => (
30 <tr key={user.id}>
31 <td>{user.name}</td>
32 <td>{user.email}</td>
33 <td>{user.phone}</td>
34 </tr>
35 ))}
36 </table>
37 </>
38 )}
39 </div>
40 )
41}
42
43export default App

Now if you run the app, you will see the data being displayed in a table:

users data displayed in a table

Source code and Demo

You can view the complete source code here and a demo here.

If you have liked article, do follow me on twitter to get more real time updates!

Leave a Comment

© 2023 CodingDeft.Com