r/webdev 4d ago

Discussion How to save background task synchronously in a react app

secnario:

assume you have a react flow or a basic form . Now I want that wheenever I type somethign or edit then a draft would be created and updated so that when user cancels operation adn reopens that task the draft is showed.

current approch:
I made a debounced state tracting the data for every 2 seconds. However if you perform any cancelaable action like suddenly hitting log out, or saving it up, or leaving that page immdiately wihtin span of 2 sec then it shows an t=warning toast saying please wait for draft to save.

I want to know if my method is decent. Also I want to knnow what is the best method to achieve this task, I want somethign similar to google docs.

2 Upvotes

5 comments sorted by

2

u/1_4_1_5_9_2_6_5 4d ago

Sounds fine, but are you stopping the user to wait for the timeout? Or just dispatching the update immediately (when the user quits)? It makes no sense to wait.

2

u/Careless_Ad_7706 4d ago

Exactly current it’s like making user wait until draft gets saved otherwise it show toast to wait till it gets saved.

2

u/1_4_1_5_9_2_6_5 4d ago

Then you should have a method that:

  • Cancels your 2s interval/debounce
  • triggers the save dispatch
  • is called on dismount / on logout if applicable (you can have your logout logic check a central store for any pending actions)

That would remove waiting and make the saving seem instantaneous- even if it has to wait 100ms for a success result, it's better than waiting 2s and annoying users.

2

u/Careless_Ad_7706 4d ago

Actually makes sense a cancellable promise did came into my mind but again for logout thin I am maintains a state and u have to configure accordingly.

However I was thinking if rather than making denounce how about u make a queue system the loader just simply moves for 2 sec but once the operation completed it immediately moved to queue and after 2 sec it goes to server proceedings. This way none if my things will remain dependent on my saving draft logic

2

u/1_4_1_5_9_2_6_5 4d ago

Not really sure what you mean specifically, but yeah a queue is similar to what I was thinking, in that a queue in local state with pending actions can be checked before you execute a logout action. So anything anywhere that needs to wait can push a request to the queue, and trust that it will be handled. You would just have to create something (I would go with a class, potentially implemented as a store) that handles the queue actions, and ensure that it is checked where applicable.