Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

svelte

How to use module context in Svelte

Yasir Latif

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:

Module context for component communication

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=0
    export function totalCount(){
        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 />

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 allCounts function 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 btnHandler that increments counter for the current component as well as the totalCount variable.

In App.svelte:

  • Line 2: We import the child component as Card and a function allCounts from index.svelte to implement module context.
  • Line 5: We define a button that calls allCounts function imported from index.svelte.
  • Line 6–8: We render the imported component multiple times.

RELATED TAGS

svelte

CONTRIBUTOR

Yasir Latif
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring