On this page
Maps
Map store can be used to store objects with one level of depth and change keys in this object.
To create map store call map(initial) function with initial object.
import { map } from 'nanostores'
export const $profile = map({ name: 'anonymous'})In TypeScript, you can pass type parameter with store’s type:
export interface ProfileValue { name: string email?: string}
export const $profile = map<ProfileValue>({ name: 'anonymous'})store.set(object) or store.setKey(key, value) methods will change the store.
$profile.setKey('name', 'Kazimir Malevich')Setting undefined will remove optional key:
$profile.setKey('email', undefined)Store’s listeners will receive third argument with changed key.
$profile.listen((profile, oldProfile, changed) => { if (changed) console.log(`${changed} new value ${profile[changed]}`)})You can also listen for specific keys of the store being changed, using
listenKeys and subscribeKeys.
listenKeys($profile, ['name'], (value, oldValue, changed) => { console.log(`$profile.Name new value ${value.name}`)})Nested mutations can be listened to using a base key. For example, listening to user will trigger on user.name mutations:
// Mutating user.name triggers the listenerlistenKeys($state, ['user'], (value, oldValue, changed) => { console.log(`user changed: ${changed}`)})subscribeKeys(store, keys, cb) in contrast with listenKeys(store, keys, cb)
also call listeners immediately during the subscription.
Please note that when using subscribe for store changes, the initial evaluation
of the callback has undefined old value and changed key.
Imported from the Nano Stores README for version 1.5.5. Improve this page there.