Svelte Svelte

Custom Stores & Store Bindings

Check out a free preview of the full Svelte course:
The "Custom Stores & Store Bindings" Lesson is part of the full, Svelte course featured in this preview video. Here's what you'd learn in this lesson:

Rich demonstrates creating a custom store, which is an object that impliments a subscribe method. Rich also demonstrates creating a custom store binding by using the writable method from svelte/store.

Get Unlimited Access Now

Transcript from the "Custom Stores & Store Bindings" Lesson

[00:00:00]
>> We can also create custom stores because remember, the store contract is very simple. You just need to have a subscribe method and anything beyond that is up to you. So if we take our count store from the first store example, then what we can do is add increment, decrement, and reset methods on the store itself.

[00:00:27] In our stores tab, we have a new function to create a special count store. And inside that we're beginning by creating a writable store just like we had before when we were doing all this ourselves. And we're destructuring it to get references to subscribe, set, and update, which are the three methods that exist on a writable store.

[00:00:49] And what we're gonna turn that into is a store where you can only change the value in specific ways. So whereas before you could have a count store and then you could do count.set potato or something irrelevant like that. This time, the store is gonna expose its own API.

[00:01:07] So our increment function is gonna look like this, exactly as we had when we had an increment the component. n plus 1 and then the same down here, update n minus 1. And then set zero. And then inside our app.svelte, we're already referencing those functions. And that works exactly as you would expect.

[00:01:45] Just as you combined two component state, you can also bind two store values. So here we have a store representing a string, which is the name of the user. And then we have another store that is derived from that store value. So we want to do is wire up this input to the value of the name store so that the greeting is automatically derived whenever that changes.

[00:02:14] So the h1 is displaying the derived value. The input is displaying the input value. And I'm going to change that into a binding, just to show that it doesn't do anything right now. Find current value, And it works exactly as a regular input would. Now we can also change the value of stores inside components either inside the script block or inside the markup.

[00:02:51] So we can add a button here. Give it an event handler every time we click it. We're gonna change the value of name directly and then now every time we press that the store value is updated. This is the same as doing this. But it's just a little bit neater.