Implementing Custom Stores
In the last chapter, we learned that a Svelte store is any object that follows a Svelte store contract, and encapsulating data within a Svelte store allows the data to be shared and used across multiple Svelte components reactively. The Svelte component keeps the DOM up to date with the data, even though the data is modified outside of the Svelte component.
We learned about two of Svelte’s built-in methods for creating a Svelte store—namely readable()
and writable()
, which create a readable and writable store. The two methods follow the Svelte contract and create a very basic Svelte store. However, besides using a Svelte store to encapsulate data, we can also encapsulate logic with the data, making the Svelte store modular and highly reusable.
In this chapter, we will be creating custom Svelte stores—Svelte stores that encapsulate custom data logic. We will go through three distinct examples; each example will serve as a guide,...