Search code examples
javascriptsveltesappersvelte-store

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!


Solution

  • .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;
    });