Search code examples
reactjsuse-effectuse-state

Using useEffect properly when making reqs to a server


I have a handleRating function which sets some state as so:

  const handleRating = (value) => {
    setCompanyClone({
      ...companyClone,
      prevRating: [...companyClone.prevRating, { user, rating: value }]
    });
    setTimeout(() => {
      handleClickOpen();
    }, 600);
  };

I think also have a function which patches a server with the new companyClone values as such:

  const updateServer = async () => {
    const res = await axios.put(
      `http://localhost:3000/companies/${companyClone.id}`,
      companyClone
    );

    console.log("RES", res.data);
  };

my updateServer function gets called in a useEffect. But I only want the function to run after the state has been updated. I am seeing my res.data console.log when I load my page. Which i dont want to be making reqs to my server until the comapanyClone.prevRating array updates.

my useEffect :

  useEffect(() => {
    updateServer();
  }, [companyClone.prevRating]);

how can I not run this function on pageload. but only when companyClone.prevRating updates?


Solution

  • For preventing function call on first render, you can use useRef hook, which persists data through rerender.

    Note: useEffect does not provide the leverage to check the current updated data with the previous data like didComponentMount do, so used this way


    Here is the code example.

    https://codesandbox.io/s/strange-matan-k5i3c?file=/src/App.js