How to Use Svelte Stores to Share Data Between Components
A Svelte store is a mechanism to share state and data between different components in a Svelte application. To use stores, you need to set up your Svelte app with Node.js, then create a new file called stores.js where you define the initial values of your stores using the writable() function for writable stores or derived() function for derived stores. You can also import and reference these store values in other components. In this example, we created three stores: itemsInCart, cartContents, and totalPrice, with the latter being a derived store that automatically updates when the value of itemsInCart changes. We then imported these stores into our App component to display their current values, and wired up an AddItem button to update these store values whenever clicked.
Company
Twilio
Date published
May 17, 2021
Author(s)
Ashley Boucher
Word count
2501
Language
English
Hacker News points
None found.