We will make use of jsonplaceholder for our APIs.
Project setup
Create a react app using the following command:
npx create-react-app react-fetch-data-table
Add the following styles in index.css
:
body {
margin-top: 20px;
display: flex;
justify-content: center;
}
Calling the API
We will use the browser fetch API inside the useEffect hook to call the API to fetch data.
import { useEffect, useState } from "react"
function App() {
const [users, setUsers] = useState([])
const [loading, setLoading] = useState(false)
useEffect(() => {
setLoading(true)
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(json => setUsers(json))
.finally(() => {
setLoading(false)
})
}, [])
return <div className="App"></div>
}
export 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
import { useEffect, useState } from "react"
function App() {
const [users, setUsers] = useState([])
const [loading, setLoading] = useState(false)
useEffect(() => {
setLoading(true)
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(json => setUsers(json))
.finally(() => {
setLoading(false)
})
}, [])
return (
<div className="App">
{loading ? (
<div>Loading...</div>
) : (
<>
<h1>Users</h1>
<table border={1}>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
{users.map(user => (
<tr key={user.id}>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.phone}</td>
</tr>
))}
</table>
</>
)}
</div>
)
}
export default App
Now if you run the app, you will see the data being displayed in a table:
Source code and Demo
You can view the complete source code here and a demo here.
Top comments (1)
As it results
Warning: validateDOMNesting(...):
We have to put tr inside thead.
<table border={1}>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
{user.map((user) => (
<tr key={user.id}>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.phone}</td>
</tr>
))}
</tbody>
</table>