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.
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.
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.
<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>
In userStore.js
:
userStore
as a writable array object with initial data in it.In userList.svelte
:
userStore
object from userStore.js
file.userStore.subscribe
function automatically whenever new data is added to the array object to fetch updated records.In userForm.svelte
:
userStore
object from userStore.js
file to write new data into the object.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
:
User
and Form
as components from userList.svelte
and userForm.svelte
file respectively to render the content for users.Free Resources