How to use module context in Svelte
Overview
The component communication has become as easy as adding a variable in the script tag as context=module. There is a need to maintain states with the help of module context instead of states. This means the increment counter from multiple components can use a single function to increment the counter value. Module context makes it possible and increments the counter of the only one component where that function is called. The code given below shows how it's done:
Let's suppose, in a certain condition, a user can select three items from different categories (components), and the cart is incremented by one each time an item is selected regardless of the components to it is added. The user can check carts to check the total number of counts. This synchronized increment is possible with the help of module context.
The index.svelte file
<script context="module">let totalCount=0export function totalCount(){return totalCount}</script><script>let count=0function btnHandler(){count += 1totalCount += 1}</script><h2>Cart counter - {count}</h2><button on:click ={btnHandler}>Increment Cart </button><hr />
The app.svelte file
<script>import Card, {totalCount} from './index.svelte'</script><div style="text-align:center;margin-top:50px;"><button on:click = {() => alert(totalCount())}>Total items</button><Card /><Card /><Card /></div>
Example
<script context="module">
let totalCount=0
export function allCounts(){
return totalCount
}
</script>
<script>
let count=0
function btnHandler(){
count += 1
totalCount += 1
}
</script>
<h2>Cart counter - {count}</h2>
<button on:click ={btnHandler}>Increment Cart </button>
<hr />Explanation
In index.svelte:
- Line 1: We define the context module as a component communication
- Line 3: We define the
allCountsfunction that is exported to return the total number of increments. - Line 10: We implement a function to increment counter value by one after clicking the button.
- Line 16: We print the counter's current value.
- Line 17: We call a function
btnHandlerthat increments counter for the current component as well as thetotalCountvariable.
In App.svelte:
- Line 2: We import the child component as
Cardand a functionallCountsfromindex.svelteto implement module context. - Line 5: We define a button that calls
allCountsfunction imported fromindex.svelte. - Line 6–8: We render the imported component multiple times.
Free Resources