Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

javascript - Altering Svelte stores from JS component with .set() not working for objects

I am kind of new to Svelte/Sapper and I am trying to update the Svelte store from a JS component.

Setting and getting the values is working fine as long as they are regular variables with no "depth"/nested objects.

I am not sure if I am doing something wrong, or if there is really no way of altering specific keys of an object without replacing the whole object.


Let me explain what I mean:

stores.js

import { writable } from 'svelte/store'

export const ui_vars = writable({
    filter_extended: false,
    menu_extended: false,
    loading: { products: true }
})

export const simple_var = writable(false)

**test.js**

import { get } from 'svelte/store';
import { simple_var, ui_vars } from "../stores";

// WORKING
console.log(get(simple_var)); // false
simple_var.set(true); // alters the simple_var from false to true (as expected)
console.log(get(simple_var)); // true

// NOT WORKING
console.log(get(ui_vars)); // outputs the object as in store
ui_vars.filter_extended.set(true); // SHOULD ALTER the ui_vars.filter_extended from false to true, but throws Error instead, ERROR: Uncaught (in promise) TypeError: (intermediate value).filter_extended is undefined
console.log(get(ui_vars)); // should output the altered object

The erro:

Uncaught (in promise) TypeError: (intermediate value).filter_extended is undefined

Can anyone explain what I am doing wrong here? Many thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.set is a function that exists on a writable.

When you do ui_vars.filter_extended it will be undefined because filter_extended doesn't exist on a writable.

If you want to set filter_extended to true, I would do:

ui_vars.update(x => {
     x.filter_extended = true;
     return x;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...