I get an array of objects from my SQL database via fetch, successfully get the array, and set it to my State. However, in the component (to which I pass the value of the State with props) that must render the objects in a table, they aren’t rendered when the State is updated.
My steps would be these: I do a fetch> I set the value to the State> I pass it through props> I apply a map to the state> Data should be rendered in rows
With a use Effect and the React devsTools I have verified that the {data} is indeed reaching my component, but it still doesn’t render. This is part of my code.
`
app.js
const [tableData, setTableData] = useState([])
async function getTableData() {
await fetch('http://localhost:2000/API/usersList').
then(response => response.json()).
then(json => {
console.log(json.response)
setTableData(json.response)})
}
useEffect(() => {
getTableData()
}, [])
`
Part of my Table.jsx
`
import React, { useEffect } from 'react'
import edit from "../../images/edit.svg"
import remove from "../../images/delete.svg"
function MainTable({data}) {
useEffect(() => {
console.log(data)
}, [data])
return (
<div>
{data.length>0?
<table>
<thead>
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Passport</th>
<th>City</th>
<th>Status</th>
<th>Level</th>
<th>Salary</th>
<th>Start Date</th>
<th>Skills</th>
<th>Actions:</th>
</tr>
</thead>
<tbody>
{data.map( (item) => {
<tr>
<td>{item.name}</td>
<td>{item.lastName}</td>
<td>{item.email}</td>
<td>{item.passport}</td>
<td>{item.city}</td>
<td>{item.status}</td>
<td>{item.level}</td>
<td>{item.salary}</td>
<td>{item.startDate}</td>
<td>{item.skills}</td>
<td>
<img src={edit} alt="edit" />
<img src={remove} alt="delete" />
</td>
</tr>
})
}
</tbody>
<button onClick={() => console.log(data)}>asasdsf</button>
</table>
:
<h1>Wait...</h1>
}
</div>
)
}
`
These components only work as intermediaries, in the future I need to add functionality to them.
function Home({data}) {
return (
<div>
<TableContainer data={data} />
</div>
)
}
function TableContainer({data}) {
return (
<div>
<MainTable data={data} />
</div>
)
}
>Solution :
Missing a return in your mapping function, since you used curly braces.
As a sidenote, the key prop is also important to include when displaying a list of elements, so that React knows when and what to re-render. I used index in the examples here, but if item has some suitably unique property, use that instead (e.g. ID).
data.map((item, index) => {
return (
<tr key={index}>
...
</tr>
);
})
Or you can omit return if you switch to regular braces:
data.map((item, index) => (
<tr key={index}>
...
</tr>
))