API reference
Reference for stores, subscriptions, lifecycle hooks and TypeScript types.
API index
Types 20
Deprecated 2
function atom<Value, StoreExt>(...args): PreinitializedWritableAtom<Value> & StoreExt;Create store with atomic value. It could be a string or an object, which you will replace completely.
If you want to change keys in the object inside store, use map.
import { atom, onMount } from 'nanostores'
// Initial valueexport const $router = atom({ path: '', page: 'home' })
function parse () { $router.set({ path: location.pathname, page: parse(location.pathname) })}
// Listen for URL changes on first store’s listener.onMount($router, () => { parse() window.addEventListener('popstate', parse) return () => { window.removeEventListener('popstate', parse) }})Type Parameters
Section titled “Type Parameters”Value
StoreExt
Section titled “StoreExt”StoreExt = object
Parameters
Section titled “Parameters”…undefined extends Value ? [] | [Value] : [Value]
Returns
Section titled “Returns”PreinitializedWritableAtom<Value> & StoreExt
The store object with methods to subscribe.
function map<Value, StoreExt>(value): PreinitializedMapStore<Value> & StoreExt;Create map store with an initial value. Map store is a store with key-value object as a store value.
Type Parameters
Section titled “Type Parameters”Value extends object
StoreExt
Section titled “StoreExt”StoreExt extends object = object
Parameters
Section titled “Parameters”Value
Initial store value.
Returns
Section titled “Returns”PreinitializedMapStore<Value> & StoreExt
The store object with methods to subscribe.
Other overloads
Call Signature
Section titled “Call Signature”function map<Value, StoreExt>(value?): PreinitializedMapStore<Partial<Value>> & StoreExt;Create map store with no initial value, or one that may be missing.
Type Parameters
Section titled “Type Parameters”Value extends object
StoreExt
Section titled “StoreExt”StoreExt extends object = object
Parameters
Section titled “Parameters”value?
Section titled “value?”Value
Initial store value, if there is one.
Returns
Section titled “Returns”PreinitializedMapStore<Partial<Value>> & StoreExt
The store object with methods to subscribe.
computed
Section titled “computed”computed<Value, OriginStores extends readonly Store[]>(stores: readonly [...OriginStores], cb: (...values: StoreValues<OriginStores>) => Value | Task<Value>): ReadableAtom<Value>Create derived store, which use generates value from another stores.
import { computed } from 'nanostores'
import { $users } from './users.js'
export const $admins = computed($users, users => { return users.filter(user => user.isAdmin)})Use @nanostores/async for async function.
Other overloads
Deprecated: Use
@nanostores/async.
computed<Value, OriginStore extends Store>(stores: OriginStore, cb: (value: StoreValue<OriginStore>) => Task<Value>): ReadableAtom<Value | undefined>Deprecated: Use
@nanostores/async.
computed<Value, OriginStores extends readonly Store[]>(stores: readonly [...OriginStores], cb: (...values: StoreValues<OriginStores>) => Task<Value>): ReadableAtom<Value | undefined>computed<Value, OriginStore extends Store>(stores: OriginStore, cb: (value: StoreValue<OriginStore>) => Value): ReadableAtom<Value>batched
Section titled “batched”batched<Value, OriginStores extends readonly Store[]>(stores: readonly [...OriginStores], cb: (...values: StoreValues<OriginStores>) => Value | Task<Value>): ReadableAtom<Value>Create derived store, which use generates value from another stores.
import { batched } from 'nanostores'
const $sortBy = atom('id')const $category = atom('')
export const $link = batched([$sortBy, $category], (sortBy, category) => { return `/api/entities?sortBy=${sortBy}&category=${category}`})Other overloads
batched<Value, OriginStore extends Store>(stores: OriginStore, cb: (value: StoreValue<OriginStore>) => Value | Task<Value>): ReadableAtom<Value>effect
Section titled “effect”effect<OriginStores extends readonly ListenableStore[]>(stores: readonly [...OriginStores], cb: (...values: StoreValues<OriginStores>) => void | (() => void)): () => voidSubscribe for multiple stores. Also you can define cleanup function to call on stores changes.
const $enabled = atom(true)const $interval = atom(1000)
const cancelPing = effect([$enabled, $interval], (enabled, interval) => { if (!enabled) return const intervalId = setInterval(() => { sendPing() }, interval) return () => { clearInterval(intervalId) }})Other overloads
effect<OriginStore extends ListenableStore>(stores: OriginStore, cb: (value: StoreValue<OriginStore>) => void | (() => void)): () => voidfunction batch(fn): void;Run multiple store changes as a single transaction. While inside batch,
listeners are deferred and each listener fires at most once when the
outermost batch returns — with the final store values.
Batches can be nested; only the outermost batch triggers the flush.
Synchronous only. The batch closes when fn returns, so writes performed
in microtasks, timers, or after await will not be batched. Pass a sync
function.
Map#setKey writes are coalesced as well, so the listener’s changed
argument is undefined for the batched notification.
import { atom, batch } from 'nanostores'
let $a = atom(0)let $b = atom(0)
batch(() => { $a.set(1) $b.set(2)})Parameters
Section titled “Parameters”() => void
Callback that performs the store writes.
Returns
Section titled “Returns”void
Store methods
Section titled “Store methods”$store.get()
Section titled “$store.get()”get(): Value;Get store value.
In contrast with ReadableAtom#value this value will be always initialized even if store had no listeners.
$store.get()Returns
Section titled “Returns”Value
Store value.
$store.set()
Section titled “$store.set()”set(newValue): void;Change store value.
$router.set({ path: location.pathname, page: parse(location.pathname) })Parameters
Section titled “Parameters”newValue
Section titled “newValue”Value
New store value.
Returns
Section titled “Returns”void
$store.setKey()
Section titled “$store.setKey()”setKey<Key>(key, value): void;Change key in store value.
$settings.setKey('theme', 'dark')To delete key set undefined.
$settings.setKey('theme', undefined)Type Parameters
Section titled “Type Parameters”Key extends string | number | symbol
Parameters
Section titled “Parameters”Key
The key name.
ValueWithUndefinedForIndexSignatures<Value, Key>
New value.
Returns
Section titled “Returns”void
$store.listen()
Section titled “$store.listen()”listen(listener): () => void;Subscribe to store changes.
In contrast with Store#subscribe it do not call listener immediately.
Parameters
Section titled “Parameters”listener
Section titled “listener”(value, oldValue) => void
Callback with store value and old value.
Returns
Section titled “Returns”Function to remove listener.
() => void
$store.subscribe()
Section titled “$store.subscribe()”subscribe(listener): () => void;Subscribe to store changes and call listener immediately.
import { $router } from '../store'
$router.subscribe(page => { console.log(page)})Parameters
Section titled “Parameters”listener
Section titled “listener”(value, oldValue?) => void
Callback with store value and old value.
Returns
Section titled “Returns”Function to remove listener.
() => void
Lifecycle
Section titled “Lifecycle”onMount
Section titled “onMount”function onMount<Shared>($store, initialize): () => void;Run constructor on first store’s listener and run destructor on last listener unsubscription. It has a debounce to prevent flickering.
A way to reduce memory and CPU usage when you do not need a store.
You can communicate between listeners by payload.shared.
import { onMount } from 'nanostores'
// Listen for URL changes on first store’s listener.onMount($router, () => { parse() window.addEventListener('popstate', parse) return () => { window.removeEventListener('popstate', parse) }})Type Parameters
Section titled “Type Parameters”Shared
Section titled “Shared”Shared = never
Parameters
Section titled “Parameters”$store
Section titled “$store”Store to listen.
initialize
Section titled “initialize”(payload) => void | (() => void)
Store constructor. Returns store destructor.
Returns
Section titled “Returns”A function to remove constructor and destructor from store.
() => void
STORE_UNMOUNT_DELAY
Section titled “STORE_UNMOUNT_DELAY”const STORE_UNMOUNT_DELAY: number;Map helpers
Section titled “Map helpers”listenKeys
Section titled “listenKeys”function listenKeys<SomeStore>( $store, keys, listener): () => void;Listen for specific keys of the store.
In contrast with subscribeKeys it do not call listener immediately.
import { listenKeys } from 'nanostores'
listenKeys($page, ['blocked'], (value, oldValue, changed) => { if (value.blocked) { console.log('You has no access') }})Type Parameters
Section titled “Type Parameters”SomeStore
Section titled “SomeStore”SomeStore extends object
Parameters
Section titled “Parameters”$store
Section titled “$store”SomeStore
The store to listen.
readonly MapStoreKeys<SomeStore>[]
The keys to listen.
listener
Section titled “listener”(value, oldValue, changed) => void
Standard listener.
Returns
Section titled “Returns”() => void
subscribeKeys
Section titled “subscribeKeys”function subscribeKeys<SomeStore>( $store, keys, listener): () => void;Listen for specific keys of the store and call listener immediately. Note that the oldValue and changed arguments in the listener are undefined during the initial call.
import { subscribeKeys } from 'nanostores'
subscribeKeys($page, ['blocked'], (value, oldValue, changed) => { if (value.blocked) { console.log('You has no access') }})Type Parameters
Section titled “Type Parameters”SomeStore
Section titled “SomeStore”SomeStore extends object
Parameters
Section titled “Parameters”$store
Section titled “$store”SomeStore
The store to listen.
readonly MapStoreKeys<SomeStore>[]
The keys to listen.
listener
Section titled “listener”(value, oldValue, changed) => void
Standard listener.
Returns
Section titled “Returns”() => void
setPath
Section titled “setPath”function setPath<T, K>( obj, path, value): T;Set a deep value by path. Copies are made at each level of path so that no
part of the original object is mutated (but it does not do a full deep copy
— some sub-objects may still be shared between the old value and the new
one). Sparse arrays will be created if you set arbitrary length.
import { setPath } from 'nanostores'
setPath({ a: { b: { c: [] } } }, 'a.b.c[1]', 'hey')// Returns `{ a: { b: { c: [<empty>, 'hey'] } } }`Type Parameters
Section titled “Type Parameters”T extends BaseDeepMap
K extends string
Parameters
Section titled “Parameters”T
Any object.
K
Path split by dots and []. Like: props.arr[1].nested.
FromPath<T, K>
Returns
Section titled “Returns”T
The new object.
getPath
Section titled “getPath”function getPath<T, K>(obj, path): FromPath<T, K>;Get a value by object path. undefined if key is missing.
import { getPath } from 'nanostores'
getPath({ a: { b: { c: ['hey', 'Hi!'] } } }, 'a.b.c[1]') // Returns 'Hi!'Type Parameters
Section titled “Type Parameters”T extends BaseDeepMap
K extends string
Parameters
Section titled “Parameters”T
Any object.
K
Path split by dots and []. Like: props.arr[1].nested.
Returns
Section titled “Returns”FromPath<T, K>
The value for this path. Undefined if key is missing.
setByKey
Section titled “setByKey”function setByKey<T>( obj, splittedKeys, value): T;Set a deep value by key. Copies are made at each level of path so that no
part of the original object is mutated (but it does not do a full deep copy
— some sub-objects may still be shared between the old value and the new
one). Sparse arrays will be created if you set arbitrary length.
import { setByKey } from 'nanostores'
setByKey({ a: { b: { c: [] } } }, ['a', 'b', 'c', 1], 'hey')// Returns `{ a: { b: { c: [<empty>, 'hey'] } } }`Type Parameters
Section titled “Type Parameters”T extends BaseDeepMap
Parameters
Section titled “Parameters”T
Any object.
splittedKeys
Section titled “splittedKeys”PropertyKey[]
An array of keys representing the path to the value.
unknown
New value.
Returns
Section titled “Returns”T
The new object.
Tasks & testing
Section titled “Tasks & testing”function task<Return>(cb): Task<Return>;Track store async task by wrapping promise callback. It is useful for test to wait end of the processing.
import { task } from 'nanostores'
async function saveUser () { await task(async () => { await api.submit('/user', user.get()) $user.setKey('saved', true) })}Type Parameters
Section titled “Type Parameters”Return
Section titled “Return”Return = never
Parameters
Section titled “Parameters”() => Return | Promise<Return>
Async callback with task.
Returns
Section titled “Returns”Task<Return>
Return value from callback.
startTask
Section titled “startTask”function startTask(): () => void;Track store async task by start/end functions. It is useful for test to wait end of the processing.
It you use async/await in task, you can use task.
import { startTask } from 'nanostores'
function saveUser () { const endTask = startTask() api.submit('/user', user.get(), () => { $user.setKey('saved', true) endTask() })}Returns
Section titled “Returns”() => void
allTasks
Section titled “allTasks”function allTasks(): Promise<void>;Return Promise until all current tasks (and tasks created while waiting).
It is useful in tests to wait all async processes in the stores.
import { allTasks } from 'nanostores'
it('saves user', async () => { saveUser() await allTasks() expect($user.get().saved).toBe(true)})Returns
Section titled “Returns”Promise<void>
cleanTasks
Section titled “cleanTasks”function cleanTasks(): void;Forget all tracking tasks. Use it only for tests. cleanStores cleans tasks automatically.
import { cleanTasks } from 'nanostores'
afterEach(() => { cleanTasks()})Returns
Section titled “Returns”void
keepMount
Section titled “keepMount”function keepMount($store): void;Prevent destructor call for the store.
Together with cleanStores is useful tool for tests.
import { keepMount } from 'nanostores'
keepMount($store)Parameters
Section titled “Parameters”$store
Section titled “$store”| Store
| MapCreator<any, []>
The store.
Returns
Section titled “Returns”void
cleanStores
Section titled “cleanStores”function cleanStores(...stores): void;Destroys all cached stores and call
It also reset all tasks by calling cleanTasks.
import { cleanStores } from 'nanostores'
afterEach(() => { cleanStores($router, $settings)})Parameters
Section titled “Parameters”stores
Section titled “stores”…(
| MapCreator<any, any[]>
| Store
| undefined)[]
Used store classes.
Returns
Section titled “Returns”void
Promise for stores destroying.
const clean: unique symbol;Advanced
Section titled “Advanced”onStart
Section titled “onStart”function onStart<Shared>($store, listener): () => void;Add listener on first store listener.
We recommend to always use onMount instead to prevent flickering
(onMount have small delay before unsubscribe callback).
See onMount to add constructor and destructor for the store.
You can communicate between listeners by payload.shared.
Type Parameters
Section titled “Type Parameters”Shared
Section titled “Shared”Shared = never
Parameters
Section titled “Parameters”$store
Section titled “$store”The store to add listener.
listener
Section titled “listener”(payload) => void
Event callback.
Returns
Section titled “Returns”A function to remove listener.
() => void
onStop
Section titled “onStop”function onStop<Shared>($store, listener): () => void;Add listener on last store listener unsubscription.
We recommend to always use onMount instead to prevent flickering
(onMount have small delay before unsubscribe callback).
See onMount to add constructor and destructor for the store.
You can communicate between listeners by payload.shared.
Type Parameters
Section titled “Type Parameters”Shared
Section titled “Shared”Shared = never
Parameters
Section titled “Parameters”$store
Section titled “$store”The store to add listener.
listener
Section titled “listener”(payload) => void
Event callback.
Returns
Section titled “Returns”A function to remove listener.
() => void
function onSet<Shared, SomeStore>($store, listener): () => void;Add listener to store chagings.
import { onSet } from 'nanostores'
onSet($store, ({ newValue, abort }) => { if (!validate(newValue)) { abort() }})You can communicate between listeners by payload.shared
or cancel changes by payload.abort().
New value of the all store will be payload.newValue.
On MapStore#setKey() call, changed value will be in payload.changed.
Type Parameters
Section titled “Type Parameters”Shared
Section titled “Shared”Shared = never
SomeStore
Section titled “SomeStore”SomeStore extends Store = Store
Parameters
Section titled “Parameters”$store
Section titled “$store”SomeStore
The store to add listener.
listener
Section titled “listener”(payload) => void
Event callback.
Returns
Section titled “Returns”A function to remove listener.
() => void
onNotify
Section titled “onNotify”function onNotify<Shared, SomeStore>($store, listener): () => void;Add listener to notifying about store changes.
You can communicate between listeners by payload.shared
or cancel changes by payload.abort().
On MapStore#setKey() call, changed value will be in payload.changed.
Type Parameters
Section titled “Type Parameters”Shared
Section titled “Shared”Shared = never
SomeStore
Section titled “SomeStore”SomeStore extends Store = Store
Parameters
Section titled “Parameters”$store
Section titled “$store”SomeStore
The store to add listener.
listener
Section titled “listener”(payload) => void
Event callback.
Returns
Section titled “Returns”A function to remove listener.
() => void
mapCreator
Section titled “mapCreator”function mapCreator<Value, Args, StoreExt>(init?): MapCreator<Value, Args>;Create function to create map stores. It will be like a class for store.
Type Parameters
Section titled “Type Parameters”Value extends object
Args extends any[] = []
StoreExt
Section titled “StoreExt”StoreExt extends object = object
Parameters
Section titled “Parameters”(store, id, …args) => void | (() => void)
Store’s initializer. Returns store destructor.
Returns
Section titled “Returns”MapCreator<Value, Args>
readonlyType
Section titled “readonlyType”function readonlyType<Value>(store): ReadableAtom<Value>;Change store type for readonly for export.
import { readonlyType } from 'nanostores'
const $storePrivate = atom(0)
export const $store = readonlyType($storePrivate)Type Parameters
Section titled “Type Parameters”Value
Parameters
Section titled “Parameters”ReadableAtom<Value>
The store to be exported.
Returns
Section titled “Returns”ReadableAtom<Value>
The readonly store.
ReadableAtom
Section titled “ReadableAtom”Store object.
Type details
Extended by
Section titled “Extended by”Type Parameters
Section titled “Type Parameters”Value = any
Properties
Section titled “Properties”readonly init: Value | undefined;Low-level attribute to read store’s initial value.
readonly lc: number;Listeners count.
readonly value: Value | undefined;Low-level method to read store’s value without calling onStart.
Try to use only ReadableAtom#get. Without subscribers, value can be undefined.
Methods
Section titled “Methods”eq(oldValue, newValue): boolean;Compares the previous and next values on every set.
Returning true means the values are the same, so the store keeps the old
value and no listener is called.
Parameters
Section titled “Parameters”oldValue
Section titled “oldValue”ReadonlyIfObject<Value> | undefined
newValue
Section titled “newValue”ReadonlyIfObject<Value>
Returns
Section titled “Returns”boolean
true if the values are equal, false otherwise.
Remarks
Section titled “Remarks”Called only by the store’s own writes, so a store that never writes never
calls it. Map#setKey uses MapStore#eqKey instead.
Before the first write, oldValue can be undefined, for instance on the
first run of a computed store.
Default
Section titled “Default”Object.isSee $store.get().
See $store.listen().
notify()
Section titled “notify()”notify(oldValue?): void;Low-level method to notify listeners about changes in the store.
Can cause unexpected behaviour when combined with frontend frameworks that perform equality checks for values, such as React.
Parameters
Section titled “Parameters”oldValue?
Section titled “oldValue?”ReadonlyIfObject<Value>
Returns
Section titled “Returns”void
off(): void;Unbind all listeners.
Returns
Section titled “Returns”void
See $store.subscribe().
WritableAtom
Section titled “WritableAtom”Store with a way to manually change the value.
Type details
Extends
Section titled “Extends”ReadableAtom<Value>
Extended by
Section titled “Extended by”Type Parameters
Section titled “Type Parameters”Value = any
Properties
Section titled “Properties”Methods
Section titled “Methods”See $store.set().
MapStore
Section titled “MapStore”Store with a way to manually change the value.
Type details
Extends
Section titled “Extends”WritableAtom<Value>
Extended by
Section titled “Extended by”Type Parameters
Section titled “Type Parameters”Value extends object = any
Properties
Section titled “Properties”Methods
Section titled “Methods”eqKey()
Section titled “eqKey()”eqKey<Key>( oldValue, newValue, key): boolean;Compares the previous and next values for a key on setKey.
Returning true means the values are the same, so the store keeps the old
value and no listener is called.
One function serves every key of the map, so the key name comes as the
third argument. The old value is undefined when the key is not in the map
yet.
Type Parameters
Section titled “Type Parameters”Key extends string | number | symbol
Parameters
Section titled “Parameters”oldValue
Section titled “oldValue”Get<Value, Key> | undefined
newValue
Section titled “newValue”Get<Value, Key> | undefined
Key
Returns
Section titled “Returns”boolean
true if the values are equal, false otherwise.
Remarks
Section titled “Remarks”Deleting an existing key skips the comparison and notifies either way. Whole-value writes use ReadableAtom#eq instead.
Default
Section titled “Default”Object.islisten()
Section titled “listen()”listen(listener): () => void;Subscribe to store changes.
In contrast with Store#subscribe it do not call listener immediately.
Parameters
Section titled “Parameters”listener
Section titled “listener”(value, oldValue, changedKey) => void
Callback with store value and old value.
Returns
Section titled “Returns”Function to remove listener.
() => void
Overrides
Section titled “Overrides”notify()
Section titled “notify()”notify(oldValue?, changedKey?): void;Low-level method to notify listeners about changes in the store.
Can cause unexpected behaviour when combined with frontend frameworks that perform equality checks for values, such as React.
Parameters
Section titled “Parameters”oldValue?
Section titled “oldValue?”ReadonlyIfObject<Value>
changedKey?
Section titled “changedKey?”AllKeys<Value>
Returns
Section titled “Returns”void
Overrides
Section titled “Overrides”set(newValue): void;Change store value.
$settings.set({ theme: 'dark' })Operation is atomic, subscribers will be notified once with the new value.
changedKey will be undefined
Parameters
Section titled “Parameters”newValue
Section titled “newValue”Value
New store value.
Returns
Section titled “Returns”void
Overrides
Section titled “Overrides”See $store.setKey().
subscribe()
Section titled “subscribe()”subscribe(listener): () => void;Subscribe to store changes and call listener immediately.
import { $router } from '../store'
$router.subscribe(page => { console.log(page)})Parameters
Section titled “Parameters”listener
Section titled “listener”(value, oldValue, changedKey) => void
Callback with store value and old value.
Returns
Section titled “Returns”Function to remove listener.
() => void
Overrides
Section titled “Overrides”Type details
Extends
Section titled “Extends”Promise<Value>
Type Parameters
Section titled “Type Parameters”Value
Properties
Section titled “Properties”[toStringTag]
Section titled “[toStringTag]”readonly [toStringTag]: string;Inherited from
Section titled “Inherited from”Promise.[toStringTag]t: true;Methods
Section titled “Methods”catch()
Section titled “catch()”catch<TResult>(onrejected?): Promise<Value | TResult>;Attaches a callback for only the rejection of the Promise.
Type Parameters
Section titled “Type Parameters”TResult
Section titled “TResult”TResult = never
Parameters
Section titled “Parameters”onrejected?
Section titled “onrejected?”((reason) => TResult | PromiseLike<TResult>) | null
The callback to execute when the Promise is rejected.
Returns
Section titled “Returns”Promise<Value | TResult>
A Promise for the completion of the callback.
Inherited from
Section titled “Inherited from”Promise.catchfinally()
Section titled “finally()”finally(onfinally?): Promise<Value>;Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The resolved value cannot be modified from the callback.
Parameters
Section titled “Parameters”onfinally?
Section titled “onfinally?”(() => void) | null
The callback to execute when the Promise is settled (fulfilled or rejected).
Returns
Section titled “Returns”Promise<Value>
A Promise for the completion of the callback.
Inherited from
Section titled “Inherited from”Promise.finallythen()
Section titled “then()”then<TResult1, TResult2>(onfulfilled?, onrejected?): Promise<TResult1 | TResult2>;Attaches callbacks for the resolution and/or rejection of the Promise.
Type Parameters
Section titled “Type Parameters”TResult1
Section titled “TResult1”TResult1 = Value
TResult2
Section titled “TResult2”TResult2 = never
Parameters
Section titled “Parameters”onfulfilled?
Section titled “onfulfilled?”((value) => TResult1 | PromiseLike<TResult1>) | null
The callback to execute when the Promise is resolved.
onrejected?
Section titled “onrejected?”((reason) => TResult2 | PromiseLike<TResult2>) | null
The callback to execute when the Promise is rejected.
Returns
Section titled “Returns”Promise<TResult1 | TResult2>
A Promise for the completion of which ever callback is executed.
Inherited from
Section titled “Inherited from”Promise.thenPreinitializedWritableAtom
Section titled “PreinitializedWritableAtom”Store with a way to manually change the value.
Type details
Extends
Section titled “Extends”WritableAtom<Value>
Type Parameters
Section titled “Type Parameters”Value
Properties
Section titled “Properties”readonly value: Value;Low-level method to read store’s value without calling onStart.
Try to use only ReadableAtom#get. Without subscribers, value can be undefined.
Overrides
Section titled “Overrides”Methods
Section titled “Methods”PreinitializedMapStore
Section titled “PreinitializedMapStore”Store with a way to manually change the value.
Type details
Extends
Section titled “Extends”MapStore<Value>
Type Parameters
Section titled “Type Parameters”Value extends object = any
Properties
Section titled “Properties”readonly value: Value;Low-level method to read store’s value without calling onStart.
Try to use only ReadableAtom#get. Without subscribers, value can be undefined.
Overrides
Section titled “Overrides”Methods
Section titled “Methods”MapCreator
Section titled “MapCreator”Type details
Type Parameters
Section titled “Type Parameters”Value extends object = any
Args extends any[] = []
MapCreator(id, ...args): MapStore<object & Value>;Parameters
Section titled “Parameters”string
…Args
Returns
Section titled “Returns”MapStore<object & Value>
Properties
Section titled “Properties”cache: object;Index Signature
Section titled “Index Signature”[id: string]: MapStore<object & Value>Methods
Section titled “Methods”build()
Section titled “build()”build(id, ...args): MapStore<object & Value>;Parameters
Section titled “Parameters”string
…Args
Returns
Section titled “Returns”MapStore<object & Value>
type Store<Value> = | ReadableAtom<Value>| WritableStore<Value>;WritableStore
Section titled “WritableStore”type WritableStore<Value> = | Value extends object ? MapStore<Value> : never| WritableAtom<Value>;AnyStore
Section titled “AnyStore”type AnyStore<Value> = Gettable<Value> & object;Type details
Type Parameters
Section titled “Type Parameters”Value = any
Type Declaration
Section titled “Type Declaration”readonly value: undefined | Value;type Atom<Value> = | ReadableAtom<Value>| WritableAtom<Value>;ListenableStore
Section titled “ListenableStore”type ListenableStore<Value> = Gettable<Value> & object;Type details
Type Parameters
Section titled “Type Parameters”Value = any
Type Declaration
Section titled “Type Declaration”listen()
Section titled “listen()”listen(listener): () => void;Parameters
Section titled “Parameters”listener
Section titled “listener”() => void
Returns
Section titled “Returns”() => void
Gettable
Section titled “Gettable”type Gettable<Value> = object;Type details
Type Parameters
Section titled “Type Parameters”Value = any
Methods
Section titled “Methods”get(): Value;Returns
Section titled “Returns”Value
StoreValue
Section titled “StoreValue”type StoreValue<SomeStore> = SomeStore extends Gettable<infer Value> ? Value : any;Type details
Type Parameters
Section titled “Type Parameters”SomeStore
Section titled “SomeStore”SomeStore
StoreValues
Section titled “StoreValues”type StoreValues<Stores> = { -readonly [Index in keyof Stores]: StoreValue<Stores[Index]> };Type details
Type Parameters
Section titled “Type Parameters”Stores
Section titled “Stores”Stores extends readonly Gettable[]
MapStoreKeys
Section titled “MapStoreKeys”type MapStoreKeys<SomeStore> = SomeStore extends MapStore ? AllKeys<StoreValue<SomeStore>> : SomeStore extends object ? K : AllKeys<StoreValue<SomeStore>>;Type details
Type Parameters
Section titled “Type Parameters”SomeStore
Section titled “SomeStore”SomeStore
DeepMapStore
Section titled “DeepMapStore”type DeepMapStore<T> = object & Omit<WritableAtom<T>, "listen" | "notify" | "setKey" | "subscribe">;Type details
Type Parameters
Section titled “Type Parameters”T extends BaseDeepMap
Type Declaration
Section titled “Type Declaration”setKey
Section titled “setKey”setKey: <K>(key, value) => void;Change key in store value. Copies are made at each level of key so that
no part of the original object is mutated (but it does not do a full deep
copy — some sub-objects may still be shared between the old value and the
new one).
$settings.setKey('visuals.theme', 'dark')Type Parameters
Section titled “Type Parameters”K extends AllPaths<T>
Parameters
Section titled “Parameters”K
The key name. Attributes can be split with a dot . and [].
FromPathWithIndexSignatureUndefined<T, K>
New value.
Returns
Section titled “Returns”void
listen()
Section titled “listen()”listen(listener): () => void;Subscribe to store changes.
In contrast with Store#subscribe it do not call listener immediately.
Parameters
Section titled “Parameters”listener
Section titled “listener”(value, oldValue, changedKey) => void
Callback with store value and old value.
Returns
Section titled “Returns”Function to remove listener.
() => void
notify()
Section titled “notify()”notify(oldValue?, changedKey?): void;Low-level method to notify listeners about changes in the store.
Can cause unexpected behaviour when combined with frontend frameworks doing equality checks for values, e.g. React.
Parameters
Section titled “Parameters”oldValue?
Section titled “oldValue?”T
changedKey?
Section titled “changedKey?”AllPaths<T>
Returns
Section titled “Returns”void
subscribe()
Section titled “subscribe()”subscribe(listener): () => void;Subscribe to store changes and call listener immediately.
import { $settings } from '../store'
$settings.subscribe(settings => { console.log(settings)})Parameters
Section titled “Parameters”listener
Section titled “listener”(value, oldValue, changedKey) => void
Callback with store value and old value.
Returns
Section titled “Returns”Function to remove listener.
() => void
BaseDeepMap
Section titled “BaseDeepMap”type BaseDeepMap = Record<string, unknown>;AllPaths
Section titled “AllPaths”type AllPaths<T, P, MaxDepth> = T extends infer U[] ? | `${P}[${number}]` | AllPaths<U, `${P}[${number}]`, Subtract<MaxDepth, 1>> | P : T extends BaseDeepMap ? MaxDepth extends 0 ? never : { [K in keyof T]-?: K extends number | string ? AllPaths<T[K], ConcatPath<P, `${K}`>, Subtract<MaxDepth, 1>> | (P extends "" ? never : P) : never }[keyof T] : P;Type details
Type Parameters
Section titled “Type Parameters”T
P extends string = ""
MaxDepth
Section titled “MaxDepth”MaxDepth extends number = 10
FromPath
Section titled “FromPath”type FromPath<T, P> = T extends unknown ? NestedArrKey<T, P> extends never ? NestedObjKey<T, P> extends never ? P extends keyof T ? T[P] : never : NestedObjKey<T, P> : NestedArrKey<T, P> : never;Deprecated
Section titled “Deprecated”deepMap
Section titled “deepMap”function deepMap<T>(init?): DeepMapStore<T>;Create deep map store. Deep map store is a store with an object as store value, that supports fine-grained reactivity for deeply nested properties.
Type Parameters
Section titled “Type Parameters”T extends BaseDeepMap
Parameters
Section titled “Parameters”T
Initialize store and return store destructor.
Returns
Section titled “Returns”DeepMapStore<T>
The store object with methods to subscribe.
getKey
Section titled “getKey”function getKey<T, K>(store, key): FromPath<T, K>;Type Parameters
Section titled “Type Parameters”T extends Record<string, unknown>
K extends string
Parameters
Section titled “Parameters”AnyStore<T>
K
Returns
Section titled “Returns”FromPath<T, K>