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.
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
userStoreas a writable array object with initial data in it.
In userList.svelte:
- Line 2: We import
userStoreobject fromuserStore.jsfile. - Line 4: We trigger the
userStore.subscribefunction automatically whenever new data is added to the array object to fetch updated records.
In userForm.svelte:
- Line 2: We import
userStoreobject fromuserStore.jsfile to write new data into the object. - Line 6: We trigger the
addUserfunction when theAdd new userbutton is clicked to read records entered by the user and save them in auserStorearray object.
In App.svelte:
- Line 2 and 3: We import
UserandFormas components fromuserList.svelteanduserForm.sveltefile respectively to render the content for users.
Free Resources