'Why use a factory for a custom store vs. just exporting an object
I'm going through the Svelte tutorial and I'm on the custom store page (https://svelte.dev/tutorial/custom-stores). The sample code is written using a factory function createCount
which is immediately called to create the store object that gets exported:
import { writable } from 'svelte/store';
function createCount() {
const { subscribe, set, update } = writable(0);
return {
subscribe,
increment: () => update(n => n + 1),
decrement: () => update(n => n - 1),
reset: () => set(0)
};
}
export const count = createCount();
What is the reason for doing it that way vs. just exporting the store object directly like this:
import { writable } from 'svelte/store';
const { subscribe, set, update } = writable(0);
export const count = {
subscribe,
increment: () => update(n => n + 1),
decrement: () => update(n => n - 1),
reset: () => set(0)
};
Solution 1:[1]
The difference is that the factory can be used to create multiple, independent stores. One store might have the value 4 and another the value 123.
In your second code block, there can only ever be a single store. Any code using the store will see the same value and when one piece of code updates the value, that is the value everyone will see. This is known as a "singleton."
That said, count
is a singleton in both cases; you'd need to call createCount
again to get another store (and to be able to do that you'd need to export the createCount
function).
So in conclusion, both pieces of code do exactly the same thing, but the code using the factory is prepared for creating multiple store instances (even if it doesn't currently do that).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |