0
0
Svelteframework~30 mins

Store contract (subscribe method) in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Create a Simple Svelte Store with subscribe Method
📖 Scenario: You are building a small Svelte app that needs to share a number value across components. To do this, you will create a custom store that follows the Svelte store contract by implementing a subscribe method.
🎯 Goal: Build a custom Svelte store object with a subscribe method that allows components to listen for changes in the store's value.
📋 What You'll Learn
Create a store object with an initial value of 0
Add a subscribe method to the store object
Implement a simple way to notify subscribers when the value changes
Add a method to update the store's value
💡 Why This Matters
🌍 Real World
Custom stores are useful when you want to share data or state between multiple Svelte components without using props or context.
💼 Career
Understanding the Svelte store contract is important for building scalable and maintainable Svelte applications, a skill valued in frontend development roles.
Progress0 / 4 steps
1
Create the initial store object with a value
Create a variable called count and set it to 0.
Svelte
Hint

Use let count = 0; to create the initial value.

2
Add a subscribers list to track listeners
Create a variable called subscribers and set it to an empty array [].
Svelte
Hint

Use const subscribers = []; to hold subscriber functions.

3
Implement the subscribe method for the store
Create a function called subscribe that takes a parameter run. Inside, add run to the subscribers array and immediately call run(count) to send the current value.
Svelte
Hint

Remember to call run(count) right after adding the subscriber.

4
Add an update method to change the value and notify subscribers
Create a function called set that takes a parameter value. Inside, set count = value and then call each function in subscribers with the new count.
Svelte
Hint

Use subscribers.forEach(run => run(count)) to notify all subscribers.