Search code examples
javascriptsveltesvelte-3

how to reference a reactive $ variable inside a svelte store?


I'll brief.

I have a reactive variable that updates everytime a user adds a product to a shoppingcart.

let cartItems = []
$: cartLength = cartitems.length;

Now I want to put the length of the cart items into icon in a different component. So I tried to create and share it with the rest of the component.

import { writable } from 'svelte/store';
export const cartItemsLength = writable("");

In my cartitems component. I tried to update the store after importing it into my component:

cartItemsLength.update(value=>{
value =  cartLength
})

But it shows undefined in my dev tools everytime. I tried $cartLength {$cartLength} So, my question, how do you assign that cartLength variable to the value inside the store update function?


Solution

  • writable store's update function should have a return value to be set in the store.

    https://svelte.dev/docs#writable

    // File cartitems.svelte
    
    import { writable } from 'svelte/store';
    
    export const cartItemsLength = writable(0);
    
    let cartItems = [];
    $: cartLength = cartItems.length;
    
    // 1. use store's update function
    cartItemsLength.update(value=> {
      return cartLength;
    });
    
    // 2. or you can just use $store if in .svelte script
    $cartItemsLength = cartLength;