I am working on a React.js app where I have a functional component which contains state array, which I declared like this const [myArray, setMyArray] = useState([])
.
I fetch some data from an API and add it to the array with no problem. But I am unable to delete an element of the array. First I delete it through the API and then I try to update the array, but it seems to not work.
Here is the code sample:
const deleteElement = (id) => {
fetch(URL,{method: "DELETE"}).then((response) => response.json()).then(deleteFromArray(id))};
const deleteFromArray = (id) => {
const filtered = myArray.filter((item) => item.id !== id);
setMyArray(filtered)
}
The filtered array is ok, it does not contain the deleted element. But I just can't figure out why the myArray does not get updated here. I am new to React so any hints would be appreciated. Thanks