最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to somehow change the value of a derived store directly? - Stack Overflow

programmeradmin7浏览0评论

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')

Share Improve this question asked Aug 20, 2022 at 14:49 user19738598user19738598
Add a ment  | 

1 Answer 1

Reset to default 13

You 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

发布评论

评论列表(0)

  1. 暂无评论