I have an Angular app where the data in a form needs to be saved to (and updated from) a Firestore database more or less instantly since 1) multiple people will be entering data on the same form, 2) other users are going to be using the real time values in another part of the application, and 3) the data needs to be saved in case of power or internet failure.
I'm using reactive forms and I've tried saving the form values by subscribing to the form changes and also by triggering individual changes on keyup. For the most part, it works ok, but sometimes the data gets lost.
For example, let's say I type something into a field (e.g. 123456789). Here is what sometimes happens:
- As I'm typing, '1234' gets saved to the database
- I continue typing '567'
- Once 1234 is updated in the database, it gets emitted to the document's valueChanges observable
- The form gets patched with '1234'
- I continue typing '89'
- The value in the input is now '123489' (discarding the 567 since that got lost when the update happened)
Is there a good way to handle this? I've tried to use debounceTime, but that sort of exacerbates the delay problem.
I've got a sample stackblitz where I simulate the firestore database delay issue (https://stackblitz.com/edit/immediate-save?file=src/app/app.component.ts).
p.s. I'd be OK with holding off on a save until the focus changes (e.g. blur or (change)), but I would also want to trigger a save if a cursor stops typing in a field, but doesn't tab to the next field