I am currently working with SvelteKit.
I have a derived
store, which is necessary because it depends on another store. Now I need to change some values in the derived
store directly. The problem is that derived
stores are not modifyable as far as my understanding goes.
Is there any way to change the value of a derived
store directly?
For example if I'd have a derived
store called tiles
which is an array of objects and I would like to change the property of one of its objects ($tiles[n].x = 'something new'
)
I am currently working with SvelteKit.
I have a derived
store, which is necessary because it depends on another store. Now I need to change some values in the derived
store directly. The problem is that derived
stores are not modifyable as far as my understanding goes.
Is there any way to change the value of a derived
store directly?
For example if I'd have a derived
store called tiles
which is an array of objects and I would like to change the property of one of its objects ($tiles[n].x = 'something new'
)
1 Answer
Reset to default 13You can make a derived store writable by simply adding a set
function.
You will need either access to the source object from which the value is derived or you need to merge the new value in a way that preserves the relevant object references. (Though in the latter case you may still need to do a dummy reassignment on the parent store, to trigger an update.)
E.g.
const parent = writable({ items: [{ name: 'pochi' }, { name: 'maru' }]});
const items = derived(parent, value => value.items);
items.set = newItems => $parent.items = newItems;
REPL