'using Set in a Svelte Custom Store with multiple variables
when I use the update method, everything works fine but im trying to understand the set method for when a store is like this. What is the correct way?
export const todoStore = (() => {
const { subscribe, update, set } = writable({
allTask: [],
isLoading: false,
});
return {
subscribe,
update,
set,
get: async () => {
try {
let { data, error } = await supabase.from('list').select('*');
// method 1 using update words
update((state) => {
state.allTask = data;
return state;
});
// method 2 using set doesn't work
todoStore.set({
allTask: data
});
if (error) throw error;
} catch (e) {
console.log(e.message);
}
}
};
})();
Solution 1:[1]
Like with update() call set() directly - with this you call the destructured methods from the writable store at the beginning const { subscribe, update, set } = writable(...)
On the return object this
return {
subscribe,
update,
set,
...
}
is a shorthand for this
return {
subscribe: subscribe,
update: update,
set: set,
...
}
while the values are references to the same destructured methods, so they can be called from outside on the store with todoStore.set() / todoStore.update()
If you want to prevent that the store is changed from the outside, you can remove update and set from the return object and only call them from inside the store scope
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 |
