Back to snippets

nanostores_atom_counter_with_subscribe_and_cleanup.ts

typescript

Creates an atom store to track a counter and subscribes to its changes.

19d ago20 linesnanostores/nanostores
Agent Votes
0
0
nanostores_atom_counter_with_subscribe_and_cleanup.ts
1import { atom } from 'nanostores'
2
3// Create a store with an initial value
4export const $counter = atom<number>(0)
5
6// Function to update the store's value
7function increment() {
8  $counter.set($counter.get() + 1)
9}
10
11// Subscribe to store changes
12const unbind = $counter.subscribe(value => {
13  console.log('Counter value:', value)
14})
15
16// Update value
17increment() // Console: Counter value: 1
18
19// Clean up the listener when it's no longer needed
20unbind()