I am creating a table and fetching data using Axios. However, I am not able to print the data – when I check, the data is being printed in the browser, but I am not able to print the particular data to a table format.
What should I change in my code?
import { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Table } from "react-bootstrap";
import axios from "axios";
export default function App() {
const [user, setUser] = useState([]);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users", (req, res) => {
res.json();
})
.then((data) => setUser({ ...user, data }))
.catch((error) => console.error(error));
});
return (
<div className="App">
<h3 className="text-primary">User List</h3>
<Table
variant="danger"
striped
bordered
hover
className="shadow-lg text-center"
>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>UserName</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{user?.data?.length > 0 &&
user.data.map((user) => {
return (
<tr key={user.id}>
<td>{JSON.stringify(user.data["data"].id)}</td>
<td>{JSON.stringify(user.data["data"].name)}</td>
<td>{JSON.stringify(user.data["data"].username)}</td>
<td>{JSON.stringify(user.data["data"].email)}</td>
</tr>
);
})}
</tbody>
</Table>
{/* <div>{JSON.stringify(user.data["data"])}</div> */}
</div>
);
}
3
Answers
for example
Replace the useEffect code as follow.
You already know that calling this api will give you an array of users so you can initialise the state as empty array as:
and when you are using
axios
then you don’t have to useres.json()
.axios
will do it for you out of the box.so, after getting data using
get
method ofaxios
it will return you a promise and you can get data from itsdata
property that is passed an first args. You can directly set state which will be an array of objects.Here I’ve destructed the object to get only the
data
property.Since
users
will be an array of objects, so you don’t have to do any check. You can directly useuser.id
to get the respective property.Codesandbox link