fireproof icon indicating copy to clipboard operation
fireproof copied to clipboard

`useDocument`'s save callback loses data from any immediately-preceding merges

Open natevw opened this issue 9 months ago • 1 comments

As I was first starting out I tried to merge and then save a document immediately via code like:

<form
  onsubmit=${(evt) => {
    let data = new FormData(evt.target);
    merge(Object.fromEntries(data));
    save();
    evt.preventDefault();
  }}
>
  …
</form>

But this saves only the initial document rather than the updated one! I don't see any of the new data from the merge call in my live query or when I refresh, the merge basically just seems to have gotten lost during the save.

One workaround would be after a merge to wait until until the component has re-rendered and then use the updated save callback. Most of the demos in the docs do ± this because they call merge(…) in the oninput/onchange handlers of the form fields, and then save() by itself in a separate event handler.


The save callback is bound to the original doc by default:

https://github.com/fireproof-storage/fireproof/blob/b5f258c7519a8d4fc41f255ec06284e2263e4243/use-fireproof/base/react/use-document.ts#L75-L88

And the merge method does not expose the new doc: https://github.com/fireproof-storage/fireproof/blob/b5f258c7519a8d4fc41f255ec06284e2263e4243/use-fireproof/base/react/use-document.ts#L104-L107

I need to get more familiar with the intended useDocument mental model overall, but I wonder if it should be tracking a working copy of the document as a ref beyond just the useState so that the various callbacks stay in sync when used together. Might be vaguely semi-related to #1188 mainly just in the UX sense of things a new user expects to be able to do, although in this case I had noticed that I was intended to save(). Just didn't realize I had to wait for a fresh render between updating and saving.

natevw avatar Feb 27 '26 21:02 natevw

Hi, I looked into this and was able to reproduce it locally.

The issue is that merge() only queues a React state update, so save() called in the same event handler still reads the document from the previous render. In my local test, merge({ input: "same tick" }); save(); persisted input: "" instead of "same tick".

I have a small local fix that keeps the current working document in a ref and has save() read from that ref. I also added a regression test for same-tick merge + save.

The use-fireproof hook tests pass locally:

pnpm --filter @fireproof/use-fireproof-test test

7 files passed, 54 tests passed, 1 skipped.

Would you prefer a PR for this, or is there a different useDocument mental model you want preserved?

webhop123 avatar May 17 '26 22:05 webhop123