react - how to update state of data after DELETE request

Viewed 1227

I am making cookbook app in React. The recipes are fetched via API. I would like to know how to update state of data after deleting some recipe with DELETE request. Right now, I need to refresh the app to receive updated data. Can you explain to me how to update the state after DELETE request?

the delete function look like this:

 function handleDelete() {
      
      fetch(url_recipes + id, 
         {method: 'DELETE'})
      .then(response => response.text())
      .then(json => console.log("Deleted!", json))
      .catch(error => console.log('Error message: ', error));
      navigate("/")
  }

in the Recipe List I am using useFetch to retrieve the data:

const { data: recipes, error, isPending  } = useFetch(url_recipes);
1 Answers

Well you can'use custom hook inside useEffect so what you can do is just pass a new parameter in useFetch hook(newParameter will hold your state data temporarily) in your useFetch custom hook as shown below:

Now After making a delete request you just need to update the newParameter state and as the state gets updated it will populate the useFetch hook state data with new data fetched from url and return it

  const useFetch = (url,newParameter) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => setData(data));
  }, [newParameter]);  //add newParameter in dependency array

  return [data];
};
Related