import { useState, useEffect } from "react";
export default function RenderTable(){
const [tableData, updateTableData] = useState([{id: 1, name: "name", price: 200, size: "size"}]);
useEffect(()=>{
fetch("/api/ManageSite").then(value => updateTableData(value.json()));
}, []);
return(
<table>
<tbody>
{tableData.map(value =>
<tr key={value.id}>
<td>{value.name}</td>
<td>{value.price}</td>
<td>{value.size}</td>
</tr>
)}
</tbody>
</table>
)
}
this error occurs, when I use map function in return(), but if I will do the same map function in useEffect(), it will work just fine, please explain why?
This could happen because is trying to map an object and not an array, so it is saying that doesn't exists the function Object.map().
First, ensure that the new state is an array.
Then, if can get results different from an aray, when rendering, to not have any page crash, ensure that is making a map on an array
{Array.isArray(tableData) && tableData.map(()=>{})
.json() returns a promise, which means in ES6 you need to use another then.
Make sure the response from backend is array in JSON format.
Then you can just:
useEffect(()=>{
fetch("/api/ManageSite")
.then(value => value.json())
.then(data => updateTableData(data))
}, []);
Because no matter what even if you do fetch and update data like I did correctly but your endpoint response is not an array. Same error will keep occurring