svelte: importing store from a component?

Advertisements

I have created a readable store in a svelte component (src/components/myComponent.svelte) like so

import { readable } from "svelte/store";

export let data;

const mags = data.magazines;
export const allMags = readable(mags);

console.log($allMags) // correct output

I want to import this store into my src/store.js file so that I can use it to create derived stores. I have tried the following:

import { writable, readable, derived } from "svelte/store";
import { allMags } from "../src/components/myComponent.svelte";
// console.log($allMags)

I have encountered the following errors:

client.ts:112 SyntaxError: The requested module ‘/src/components/myComponent.svelte?t=1696086887675’ does not provide an export named ‘allMags’ (at stores.js?t=1696086887675:2:10)

Obviously, logging $allMags didn’t work and I received this error:

|- ReferenceError: $allMags is not defined  
   at eval (src/stores.js:8:13)  
   at async instantiateModule (/node_modules/vite/dist/node/chunks/dep-e8f070e8.js:54405:9)

Internal server error: $allMags is not defined

I think (I am a svelte noob) the issue is originating in the import of allMags in the store.js file. Is this not allowed? If it is allowed, how can I fix the import statement?

>Solution :

  1. You cannot import a store from a component unless it is exported from the context="module" script. Any other export is a property on a component instance.
  2. Even if you do that, you cannot use $store syntax outside of Svelte files. To the get the store value once, use the get utility function. To continually receive store change notifications, use the subscribe function on the store itself.

Leave a ReplyCancel reply