My code is straight forward and it looks like I am using list as the local state and have updated it once data are fetched, the list is perfectly loading on the tbody but still is undefined inside handleDelete
const [list, setList] = useState([]);
useEffect(async () => {
fetchData();
}, []);
async function fetchData() {
const { data } = await supplier.listSupplier();
setList(data.data);
}
const confirmDelete = (id) => {
alertify.confirm(() => {
handleDelete(id);
});
};
const handleDelete = async (id) => {
console.log("list>>", list); //returning undefined
const originalList = list;
const list = list.filter((r) => r.id !== id); // throwing Cannot read property 'filter' of undefined
setState(list);
try {
await supplier.deleteSupplier(id);
alertify.success("Successfully Deleted");
} catch (ex) {
if (ex.response && ex.response.status === 404) {
toastify.error("Already Deleted.");
}
setState(originalList);
}
};
return(
<tbody>
{list &&
list.map((row, i) => (
<tr key={row.id}>
<td>
<button
className="btn btn-danger btn-xs"
title="Delete"
onClick={() => confirmDelete(row.id)}
>
<i className="fas fa-trash"></i>
</button>
</td>
</tr>
))}
</tbody>
)
Here, on handleDelete()
its throwing error throwing Cannot read property 'filter' of undefined
and its obvious that list seems to be undefined down there. How could I fix this?