0

I'm working wtih a requirement where I have to send to the server whatever a user types in a form (even if he doesn't submit it).

Before hooks I would use componentWillUnmount and grab all the state variables and send it to the backend, easy peasy.

Now with hooks things changed and this is where my struggles start. I know that I can achieve the ComponentWillUnmount with this:

useEffect(() => {
    return () => {
        //the code for unmount
    }
}, []);

However this is not as simple as I need to have a variable in the useeffect "[]" or i will run into stale closure problem as describbed here Why can't useEffect access my state variable in a return statement? . What this means is that if I leave it as "[]" my state variables will be null.

My question is how would it be a clean solution? I don't have a variable that I know that it will necessarily change in the particular form, so I don't have a good variable to put on the "[]".

I thought that maybe I would create a "dirty" variable that if at least one field changed it would set it to true and I could use this variable for the [] in the useEffect, but this seems like a bit of work for something that should be much simpler.

Does anyone has a clue of an elegant solution for this?

João G.
  • 43
  • 4
  • 1
    Can you tell what exactly you want to cleanup? Add a minimal reproducible example in the question. – vighnesh153 Oct 17 '22 at 15:05
  • For this use case I don't want to necessarily clean up anything. I want to grab a bunch of variables in the state and send to the backend the information the user filled in the form – João G. Oct 17 '22 at 15:20
  • Why not send them at every change (with debounce)? Why wait for the component to unmount? – vighnesh153 Oct 17 '22 at 15:24
  • I thought about that, but in this particular case it wouldn't be good as it would generate a lot of requests and very quickly the server would be in trouble to deal with such a big amount of requests – João G. Oct 17 '22 at 15:33
  • If you still want to do it only on unmount, then maybe you can store your data in `useRef` instead of `useState` and then use the ref to get the latest data in unmount code. [Do note that using refs doesn't re-render the component on changes to the object. You will have to manually trigger re-render. or, you could probably keep using `useState` and whenever something in your state changes, update it in the ref] – vighnesh153 Oct 17 '22 at 15:33
  • 1
    I think you are trying to do something like auto save. Your server should, ideally, scale to handle the big volume of requests. If not, you could probably increase the `debounce` time to reduce the number of requests. Most of the time, your server is going to be idle, so, why not just make it work – vighnesh153 Oct 17 '22 at 15:34
  • thanks for poiting for the debounce solution, will use it for it. seems the best one for this – João G. Oct 18 '22 at 15:09

0 Answers0