I'm fetching data from an endpoint, and if I use a console.log(data)
it shows it correctly.
I only want data.data
, so I use console.log(data.data)
and apparently It show correctly what I need.
My problem is that I'm trying to show all clients in a table, but it only shows one of them.
This is my code:
import { useEffect, useState } from "react";
function Activity() {
function LoadActivity() {
fetch("https://localhost:7079/client/listClient")
.then((response) => {
return response.json()
})
.then((data) => {
setActivity([data.data])
});
}
const [actividad, setActivity] = useState([]);
useEffect(() => {
LoadActivity();
}, []);
return (
<div>
<h1>Cliente</h1>
<table>
<thead>
<tr>
<th>Id</th>
<th>name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{
actividad.map((client, i )=>(
<tr key={client[i].id}>
<td>{client[i].name}</td>
<td>{client[i].Email}</td>
<td>{client[i].id}</td>
</tr>
))
}
</tbody>
</table>
</div>
);
}
export default Activity;
And this is how it displays:
I tried to do it like this question 3 years ago.
I'm very new with React, and I don't know what I'm missing.
map
expects a function taking each item being mapped and an optional index. You’re using the index to access each item as an array, which your data image indicates is incorrect (the data should be posted as formatted text, not a link to an image). The data has neither name
nor Email
attributes—you should access properties that exist. srings
that I'm trying to show them in a <td>
setActivity([data.data])
sets activity
to be an array with one element. If data.data
is an array, setActivity(data.data)
and change your map to not index into the element. function LoadActivity() {
fetch("https://localhost:7079/client/listClient")
.then((response) => {
setActivity(response.data.data)
}).catch((error) => console.log(error));
}
also inside your jsx
you are tring to get Email
and name
propreties
<td>{client[i].Email}</td>
<td>{client[i].name}</td>
these propreties does not exist in client
object
you should map like this :
{
actividad.map((client, i )=>(
<tr key={i}>
<td>{client.id}</td>
</tr>
))
}
map
, nothing is displayed. I have this console.log(error) => Cannot read properties of undefined (reading 'data')
LoadActivity
function as above ? This is how I resolved it
const [equipo, setEquipo] = useState([]);
useEffect(() => {
obtenerDatos();
}, []);
const obtenerDatos = async () =>{
const datos = await fetch('https://localhost:7079/cliente/listarClientes')
const clientes = await datos.json()
setEquipo(clientes.data)
}