Stores


Sometimes we want to trigger some actions or pass some data to other components no matter where they are placed inside the page.

To do this, we can use a fouita builtin version of svelte stores.

<!-- Cm1.svelte -->
<script>
 let data = {name: 'fetched data from server'}
 window.Fouita.Store('myData', data)
</script>

We can use the $ sign or subscribe function to access data like svelte store autosubscription

<script>
 $: data = window.Fouita.Store('myData')
</script>

<div>
  {$data?.name}
</div>

We can update the store using the assign operator, or using the set method

<script>
 let data = window.Fouita.Store('myData')
 data = {name: "new data!"}

 // or we can use set
 data.set({name: "new data set"})

 // using update
 data.update(d => {
  d.name = "new data updated"
  return d
 })
</script>
....

Persist data to localStorage

We can also save data to localStorage directly from the store object using the "save" method

let userStore = window.Fouita.Store('userInfo', {})

userStore.save({email: "[email protected]", token: "123456789"})

Now even when we refresh the page the user will still accessible, to delete it we can use "clear" method

userStore.clear()