automerge / automerge-repo

MIT License
419 stars 43 forks source link

bugfix: avoid returning stale data in useDocument and useHandle #347

Closed geoffreylitt closed 2 months ago

geoffreylitt commented 2 months ago

useDocument and useHandle had a footgun where after the input url changed, they would continue returning the old doc/handle for the previous input for 1 or more renders.

This behavior could cause problems in downstream computations or useEffect hooks which did not account for this brief inconsistency.

This patch fixes the problem by checking whether the input and output match before returning out of the hook. In useHandle we can just check the handle URL directly; in useDocument we need to store some additional state to remember the URL associated with a given doc.

tests

pvh commented 2 months ago

I took a stab at simplifying this patch a bit @geoffreylitt -- useHandle it turns out could be mostly deleted and I wanted to at least take a stab at simplifying useDocument. This is where I wound up. On the whole I'm increasingly convinced that we should be using some kind of state management library instead of this but hey, here we are.

Tests pass, but note that enabling or disabling the setDoc(v) on line 53 has no effect on the success of the tests.

geoffreylitt commented 2 months ago

@pvh I simplified the code further based on your idea, and I also improved the tests to ensure that URL changes lead to immediately updated data on first render.

pvh commented 2 months ago

Merged & shipped in 1.1.10.