Replies: 1 comment 3 replies
-
Hi @axzr! Maybe you could temporarily dispose the Example import { addDisposer, applySnapshot, onSnapshot, types } from "mobx-state-tree";
import {
doc,
onSnapshot as onFirestoreSnapshot,
setDoc
} from "@firebase/firestore";
const Model = types
.model({
foo: "bar"
})
.actions((self) => {
let snapshotDisposer;
const listen = () => {
snapshotDisposer = onSnapshot((snapshot) => {
setDoc(doc(db, "foo", "bar"), snapshot);
});
};
const unlisten = () => {
snapshotDisposer();
};
return {
afterCreate() {
// ...
self.foo = "baz";
// Set up the MST snapshot listener...
listen();
const firestoreUnlisten = onFirestoreSnapshot(
doc(db, "foo", "bar"),
(doc) => {
// ... but temporarily disable it when applying a Firestore
// snapshot as to not create infinite loops.
unlisten();
applySnapshot(doc.data());
listen();
}
);
// Dispose the listeners when the model is destroyed.
addDisposer(self, () => {
unlisten();
firestoreUnlisten();
});
}
};
}); |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi folks,
I've hit a weird infinite loop bug seemingly in an interaction between mst and firestore. I've found a fix, but it feels like a hack so I'm hoping that the community might have a better suggestion for me.
Here's the issue
I get that maybe creating and updating the model 'close together' could be bad, and could lead to over-writing one version or the other. I don't get how this causes an infinite loop of swapping between the two versions.
I fixed the issue by adding a timeout at point 2 above. It was a hunch after trying a bunch of other stuff.
I'm not actually asking for a fix to the infinite loop, as such. I guess what I'm asking, is there a best practice for how to go about creating/updating a model in quick succession? It's done essentially synchronously, whereas (I believe) the onSnapshot triggers are going to fire asynchonously? That seems like a bad match.
I was thinking of debouncing the save function within onSnapshot, but again, just wondering what best practise is?
Sorry if my explanation isn't great. I'm still new to mst.
Cheers!
Beta Was this translation helpful? Give feedback.
All reactions