1

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.

  • 1
    Did you try something like: `axios.post("url", object).then(() => setFetchData(Date.now()));`. Otherwise the update will be triggered before the request is actually done. – Gabriel Pichot Sep 05 '22 at 23:12
  • 1
    I suspect `.then(() => setFetchData(Date.now()))` in the child would solve your issue. – Gerrit0 Sep 05 '22 at 23:12
  • I'll try it and update tomorrow when I do some more thorough testing. For now I want to ask, exactly what are the consequences of forgetting the arrow notation? I'm still somewhat new to JS syntax, and the problem seemed to be quite subtle. – Mefistofeles Sep 05 '22 at 23:23
  • You guys were correct, the problem has been solved. – Mefistofeles Sep 06 '22 at 22:53

0 Answers0