2

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

jloosli
  • 2,461
  • 2
  • 22
  • 34
  • I tried the same in Vue.js. Same results, sometimes even the whole document gets cleared... – Flo s Nov 14 '19 at 17:55

1 Answers1

0

How does adding debounce time exacerbates delay problem? Just add debounce on valueChanges lisener, not database request:

  this.controls.valueChanges
    .pipe(
      debounceTime(500)
    )
    .subscribe(person=>{
      console.log(person);
      this.dataSvc.updatePerson(person);
    });
lemek
  • 799
  • 10
  • 21
  • 1
    It doesn't necessarily exacerbate the problem...it depends on the cadence of typing. For example, if I type 1234, pause until the debounce ends (and the save is triggered), then type 567890, I might get 123490 – jloosli Feb 04 '19 at 17:06