Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access nested store with dollar sign syntax

Tags:

svelte

I'm trying to decide on a unified pattern/interface for svelte custom stores. I find it useful to not only export the basic state of the store, but also expose some kind of getters. I can't seem to find a way to use sveltes $-syntax to access the nested stores when not destructured on import though:

User.store.js (simplified)

import { readable, writable } from 'svelte/store';

const store = writable({
    token: null,
});

const loggedIn = readable(false, (set) => store.subscribe(s => set(!!s.token)));

const login = async (token) => store.set({token});
const logout = async () => store.set({token: null};

const state = {subscribe: store.subscribe}

export {state, loggedIn, login, logout}
export default {state, loggedIn, login, logout}

Index.svelte

<script>
import {loggedIn} from './User.store.js'
import NameSpaced from './User.store.js'
import {loggedIn as NameSpacedLoggedIn} from './User.store.js'

</script>

LoggedIn 1: {$loggedIn} // WORKS, BUT NOT NAMESPACED (false)
LoggedIn 2: {NameSpaced.$loggedIn} // DOES NOT WORK (undefined)
LoggedIn 3: {$NameSpaced.loggedIn} // DOES NOT WORK (undefined)
LoggedIn 4: {$NameSpacedLoggedIn} // WORKS, BUT CUMBERSOME (false)

Question

How to access store with the dollar-syntax when nested/namespaced?

like image 725
Seltsam Avatar asked Jun 25 '26 20:06

Seltsam


1 Answers

Autosubscription on nested stores is not supported in Svelte as of now. You have to unnest an then subscribe to it. In addition to the various ways that work that you have shown, you could also do:

<script>
import NameSpaced from './User.store.js'

const loggedIn = NameSpaced.loggedIn;
</script>
LoggedIn: {$loggedIn}
like image 152
dummdidumm Avatar answered Jun 30 '26 06:06

dummdidumm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!