React JS - Using Date.now() to change the state and rerender a component is unreliable

Viewed 23

I'm working on a personal project.

I have a simple system that for now is just the CRUD operations. I have a parent component that fetches a list of objects using axios.get. This component passes the list of objects to several children that display them, along with buttons to delete or edit them. The problem is, I need to re-render the parent component every time a deletion or edition occurs. The way I solved it is declaring a state variable in the parent, a useEffect hook that refetches the objects whenever said variable changes, and making the children change the variable as needed.

Parent:

const [fetchData, setFetchData] = useState(0);

useEffect(() => {
    axios.get("url").then(response => {
      setObjects(response.data)});
  }, [fetchData]);

As for the child, it recieves a setReFetchData as prop and sets the current time after finishing the relevant axios request:

axios.post("url", object).then(setFetchData(Date.now()));

This admittedly wonky yet funny way of doing it works great... 95% of the time. It seems that sometimes it does not trigger the rerender, yet I'm not clicking the buttons several times per millisecond.

I have searched this issue, and didn't found anything relevant to this very specific problem.

EDIT: I have no idea why this was marked as a duplicate. The supposed duplicate question has nothing to do with mine. The solution has been given in the comments, however.

0 Answers
Related