S
SolidJS2mo ago
Ditto

How can I synchronize two stores without running into an infinite loop?

The following code triggers an infinite loop:
const [store1, setStore1] = createStore({a: 1, b: 2});
const [store2, setStore2] = createStore();

createEffect(() => {
setStore1(store2);
});

createEffect(() => {
setStore2(store1);
});
const [store1, setStore1] = createStore({a: 1, b: 2});
const [store2, setStore2] = createStore();

createEffect(() => {
setStore1(store2);
});

createEffect(() => {
setStore2(store1);
});
How can I update one when the other changes and avoid this?
6 Replies
mrVinicius
mrVinicius2mo ago
what is the actual use case behind this?
Ditto
Ditto2mo ago
I'm using felte (https://felte.dev/docs) for form state management, but I want to have a copy of the form's values higher in the component hierarchy so that I can keep the state between mounts/unmounts.
Felte | Documentation
An extensible form library for Svelte, Solid and React.
Ditto
Ditto2mo ago
So my idea was: copy felte's data store whenever it changes to another store and restore it's state using the cached one when it mounts again. I could just move the createForm call to a parent component, but then it would be far away from where it is actually used.
mrVinicius
mrVinicius2mo ago
it seems the form is the source of truth, why don't have a single createEffect?
Ditto
Ditto2mo ago
How would that work? I want to 1. Cache form state when it changes. 2. Restore form state when it remounts using the cached form state.
mrVinicius
mrVinicius2mo ago
what i can think of is the data should flow from the form store to cache store, and when mounting again you could emit a single set operation to put the data back into the form. one createEffect to keep your cache fresh as the form gets updated, and one onMount() put the data back in the form store
Want results from more Discord servers?
Add your server
More Posts