Search code examples
storesvelte

Accessing svelte store with $ notation causing Reference Error


I have a store.js file whose content is :

import { writable } from 'svelte/store';
export  const generateds = writable(0);

console.log("generateds", $generateds)

Each time I try to access $generateds (inside or outside this file) I get this error :

Uncaught ReferenceError: $generateds is not defined
    at stores.js:4
    at main.js:6

When I use a store in a new project, there is no problem. I can't find what's the problem in my current project.

Here is the list of the npm packages I'm using :

── @fortawesome/free-solid-svg-icons@5.14.0
├── @material/layout-grid@7.0.0
├── @mdi/js@5.9.55
├── @rollup/plugin-commonjs@17.1.0
├── @rollup/plugin-node-resolve@11.2.0
├── @smui/button@1.0.0
├── @smui/card@1.0.0
├── @smui/drawer@1.0.0
├── @smui/fab@1.0.0
├── @smui/icon-button@1.0.0
├── @smui/list@1.0.0
├── @smui/select@1.0.0
├── @smui/textfield@1.0.0
├── @smui/top-app-bar@1.0.0
├── @sveltejs/svelte-virtual-list@3.0.1
├── autoprefixer@9.8.6
├── dropzone@5.7.2
├── eslint-plugin-svelte3@2.7.3
├── eslint@7.9.0
├── firebase@7.24.0
├── firestore-export-import@0.10.0
├── mathlive@0.59.0
├── node-sass@4.14.1
├── postcss@8.2.6
├── query-string@6.13.2
├── rollup-plugin-analyzer@4.0.0
├── rollup-plugin-css-only@3.1.0
├── rollup-plugin-livereload@2.0.0
├── rollup-plugin-postcss@4.0.0
├── rollup-plugin-sass@1.2.2
├── rollup-plugin-svelte@7.1.0
├── rollup-plugin-terser@7.0.2
├── rollup@2.39.0
├── sass@1.32.7
├── sirv-cli@1.0.11
├── svelte-fa@2.1.1
├── svelte-loading-spinners@0.1.1
├── svelte-materialify@0.3.5
├── svelte-preprocess@4.6.9
├── svelte-routing@1.5.0
├── svelte@3.32.3

Solution

  • The $ syntax to reference a store value can only be used inside a Svelte component. From the docs (emphasis mine):

    Any time you have a reference to a store, you can access its value inside a component by prefixing it with the $ character. This causes Svelte to declare the prefixed variable, and set up a store subscription that will be unsubscribed when appropriate.

    If you need to get the value inside a normal JS file, you can either subscribe to it or use Svelte's get function (which subscribes to the store to get the value and immediately unsubscribes).

    import { generateds }  from './store.js';
    import { get } from 'svelte/store';
    
    // method 1
    const unsubscribe = generateds.subscribe((val) => { console.log(val); });
    unsubscribe();
    
    // method 2
    console.log(get(generateds));