Learn How To Use Svelte Store
In this article, we will Learn How To Use Svelte Store.
What Is Store
A Store is an object which has methods like subscribe, update and set. If you want to pass some values with other components, you can do it with props or dispatching events but sometimes it gets complicated if your app is huge.
Stores can be used globally, you just need to import it and use it with whichever component you want.
Creating Writable Store
countStore.js
import {writable} from 'svelte/store'
export let count=writable(0)
Here we have imported the writable from svelte/store and created a variable with a default value of 0 inside writable. Then we have exported the count variable to use in our components.
NOTE: In order to create writable stores you have to create a JavaScript file and not svelte.
Creating Increment Button
Increment.svelte
<script>
import {count} from './countStore.js'
</script>
<button on:click={()=>{$count++}}>
Increment
</button>
Here we have imported the writable store which we created above. After importing we have created a button with a callback that increments the value of count. If you noticed we have a $ before the count it is because in order to subscribe and update the value of the store you have to use $ before that store variable.
Creating Home Page
App.svelte
<script>
import {count} from './countStore.js'
import Increment from './Increment.svelte'
</script>
<Increment />
<h2>
{$count}
</h2>
Here we have imported the Increment component and count store, we have a <h2> tag with the value of count store with $ symbol before it.