Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access Svelte store from external js files?

I am wondering if i would be able to access my Svelte store values from a plain .js file.

I am trying to write functions returning a dynamic value based on a store value, to import them in any component. But in a plain .js file I can't just access the store value with the $ sign..

Quick exemple of a basic function that uses a store value and could be used on multiple components:

//in .svelte

function add() {
    $counter = $counter + 1;
 }

EDIT: rephrasing a bit

EDIT: Found a solution but i don't really know if it's really optimized..

//in .js file

import { get } from "svelte/store";
import { counter } from "./stores";

export function add() {
    var counterRef = get(counter);
    counter.set(counterRef + 1);
}
like image 929
Joseph Allain Avatar asked Dec 01 '19 14:12

Joseph Allain


People also ask

How do I get store data from svelte?

Use get(store) to access a stores value. If you are accessing a store from within a . svelte component, there is a shortcut. Just prefix the store name with $ , eg.

Are svelte stores reactive?

What I like about Svelte stores though is that it feels simpler and easier to use. Stores are also reactive, which means that if a store value is updated anywhere, all the components using that store will reflect the updated value.

What are stores in svelte?

Svelte stores offer similar features for state management. A store is an object with a subscribe() method that allows interested parties to be notified whenever the store value changes, and an optional set() method that allows you to set new values for the store. This minimal API is known as the store contract.

How do I update my svelte store?

Click the stores. js tab to see the definition of count . It's a writable store, which means it has set and update methods in addition to subscribe . Clicking the + button should now update the count.


2 Answers

Yes, absolutely.

For one thing, the store API is very simple and nothing prevents you from subscribing to the store yourself to know the value:

import myStore from './stores'

myStore.subscribe(value => {
  // do something with the new value
  // you could store it for future reference...
})

And, if you just want to know the current value, Svelte has a helper for that, the get function:

import { get } from 'svelte/store';

import myStore from './stores'

const value = get(myStore);
like image 183
rixo Avatar answered Sep 17 '22 20:09

rixo


In addition to rixo's answer, a better way to implement add is to use the store's update method:

import { counter } from "./stores";

export function add() {
    counter.update(n => n + 1);
}

You could also create a custom store that implemented that logic.

like image 32
Rich Harris Avatar answered Sep 19 '22 20:09

Rich Harris