How to use stores in Svelte

Overview

The svelte stores come in handy in scenarios where there is a need to embed plenty of data and features in the web application to reduce the complexity. They are built-in stores and enable the developers to get out of the component's hierarchy and complexity. The svelte store can hold an array of objects or even a single object with different permissions to users like readable, writable, custom, and derived.

Stores for component communication

A userStore is created as a writable array of objects. The $ keyword is used to write the data to the store by importing userStore in userForm. As userStore is a reactive component, it can be used anywhere in the application by importing it into the relevant files.

Example

In the example below, an object of array is created with data inside it (treated as store). The object is imported by other files in which there are functions to display the data in the application as a list. It also adds new data as well in the object using forms. The updates in data are triggered automatically to the list being displayed immediately as a function is called as soon as new data is inserted in the object. As a result, a list of users is displayed with a simple form to add new user in the list.

Code

<script>
    import userStore from './userStore.js'
    let name;
    let id;

    const addUser = () =>{
        $userStore = [{user_name:name, user_id:id},...$userStore,];
    }
</script>
<input type="text" bind:value={name} placeholder="Enter user name"/>
<input type="text" bind:value={id} placeholder="Enter user id"/>
<button on:click={addUser}> Add New user</button>

Explanation

In userStore.js:

  • Line 1: We import a writable module from Svelte libraries to create a writable object.
  • Line 3: We define userStore as a writable array object with initial data in it.

In userList.svelte:

  • Line 2: We import userStore object from userStore.js file.
  • Line 4: We trigger the userStore.subscribe function automatically whenever new data is added to the array object to fetch updated records.

In userForm.svelte:

  • Line 2: We import userStore object from userStore.js file to write new data into the object.
  • Line 6: We trigger the addUser function when the Add new user button is clicked to read records entered by the user and save them in a userStore array object.

In App.svelte:

  • Line 2 and 3: We import User and Form as components from userList.svelte and userForm.svelte file respectively to render the content for users.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved