Not able to get the Svelte store data in Svelte file

Viewed 156

I am using Svelte to develop my project.

I used the Svelte store to save the user details.

In store.js define userDetails variable.

export let userDetails = writable({})

After login stored userDetails in /login/index.js

userDetails.set(user)

Now trying to access this set user details in __layout.svelte

import { userDetails } from '$lib/stores/store'

When I'm trying to get value from the store it shows the value for a few seconds and after that, it displayed 'undefined'

In the terminal, userDetails are get displayed properly, but while trying to get details on the browser it shows an undefined and an empty array.

1 Answers

To reference the value of your store in a Svelte file you use $ in front of the variable name.

Example:

<p>{$userDetails.name}</p>

Or inside a <script> tag:

const name = $userDetails.name

Replace name with any property you want to get.

You can also get the full UserDetails object with $UserDetails

I recommend looking at the Svelte Docs for more details on how stores work.

Related