Universal Reactivity and State Inspection in Svelte

Introduction to Universal Reactivity in Svelte

Creating a Reactive Cart Store

Using Getters and Setters for State Management

For mutable exported states like discount, where we expect a new value to be passed, we need to use getter and setter functions. This ensures controlled updates and prevents unintended modifications.

TypeScript
let discount = $state(0); // New state for discount

export const setDiscount = (val: number) => {
  discount = val;
};

export const getDiscount = () => discount;

By using setters for state values like discount, we ensure that state updates are properly managed, keeping reactivity intact while maintaining control over modifications.

Usage in a component:

Svelte
<script lang="ts">
  import { setDiscount, getDiscount } from '$lib/cartStore.svelte.ts';

  function applyDiscount() {
    setDiscount(10);
  }
</script>

<p>Current Discount: {getDiscount()}</p>
<button onclick={applyDiscount}>
  Apply $10 Discount
</button>
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal