What are Custom stores?
Typically in a store (Writable), there are three methods:
- subscribe()
- set()
- update()
As long as we implemented the subscribe() method, the javascript object is a store.
A store provides reactive data that can change over time. What if we want to create stores that restrict updates? It makes sense on large web/mobile applications, where we put restrictions on other components to overwrite the store variables. In other words, we allow store variables to update within the store only.
To create a custom store:
- Create a writable store in a function
- Return subscribe() function on an object.
Let's assume we have a shopping cart, and we need to add or remove items from there. In this example, we only increase or decrease the count of the cart. We start with a simple prototype and then move to more complicated in the upcoming articles.
Create a new file shoppingcart.js
under the src
directory.
import { writable } from 'svelte/store';
function addOrRemoveCartItems() {
const { subscribe, set, update } = writable(0);
return {
subscribe,
add: () => { update(n => n + 1) },
// Shopping Cart doesnot contain Negative Items
remove: () => { update(n => n <= 0 ? 0 : n - 1 ) },
resetCart: () => { set(0) }
};
}
export const items = addOrRemoveCartItems();
And in the App.svelte
<script>
import { items } from "./shoppingcart";
</script>
<main>
<p> Custom Store Example. </p>
<h1> Total Cart Items { $items }</h1>
<button on:click={ items.add }> Add to Cart </button>
<button on:click={ items.remove }> Remove from Cart </button>
<button on:click={ items.resetCart }> Remove All Items </button>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
Refresh the page and it'll look like this
In this article, we learn about custom stores. See you in the upcoming articles.
Top comments (0)