# API reference

Reference for stores, subscriptions, lifecycle hooks and TypeScript types.

## Main

### atom

```ts
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](/docs/api/#map).

```js
import { atom, onMount } from 'nanostores'

// Initial value
export 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

##### Value

`Value`

##### StoreExt

`StoreExt` = `object`

#### Parameters

##### args

…`undefined` *extends* `Value` ? \[] | \[`Value`] : \[`Value`]

#### Returns

[`PreinitializedWritableAtom`](/docs/api/#type-preinitializedwritableatom)<`Value`> & `StoreExt`

The store object with methods to subscribe.

### map

```ts
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

###### Value

`Value` *extends* `object`

###### StoreExt

`StoreExt` *extends* `object` = `object`

##### Parameters

###### value

`Value`

Initial store value.

##### Returns

[`PreinitializedMapStore`](/docs/api/#type-preinitializedmapstore)<`Value`> & `StoreExt`

The store object with methods to subscribe.

Other overloads

#### Call Signature

```ts
function map<Value, StoreExt>(value?): PreinitializedMapStore<Partial<Value>> & StoreExt;
```

Create map store with no initial value, or one that may be missing.

##### Type Parameters

###### Value

`Value` *extends* `object`

###### StoreExt

`StoreExt` *extends* `object` = `object`

##### Parameters

###### value?

`Value`

Initial store value, if there is one.

##### Returns

[`PreinitializedMapStore`](/docs/api/#type-preinitializedmapstore)<`Partial`<`Value`>> & `StoreExt`

The store object with methods to subscribe.

### computed

```ts
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.

```js
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`.

```ts
computed<Value, OriginStore extends Store>(stores: OriginStore, cb: (value: StoreValue<OriginStore>) => Task<Value>): ReadableAtom<Value | undefined>
```

> Deprecated: Use `@nanostores/async`.

```ts
computed<Value, OriginStores extends readonly Store[]>(stores: readonly [...OriginStores], cb: (...values: StoreValues<OriginStores>) => Task<Value>): ReadableAtom<Value | undefined>
```

```ts
computed<Value, OriginStore extends Store>(stores: OriginStore, cb: (value: StoreValue<OriginStore>) => Value): ReadableAtom<Value>
```

### batched

```ts
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.

```js
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

```ts
batched<Value, OriginStore extends Store>(stores: OriginStore, cb: (value: StoreValue<OriginStore>) => Value | Task<Value>): ReadableAtom<Value>
```

### effect

```ts
effect<OriginStores extends readonly ListenableStore[]>(stores: readonly [...OriginStores], cb: (...values: StoreValues<OriginStores>) => void | (() => void)): () => void
```

Subscribe for multiple stores. Also you can define cleanup function to call on stores changes.

```js
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

```ts
effect<OriginStore extends ListenableStore>(stores: OriginStore, cb: (value: StoreValue<OriginStore>) => void | (() => void)): () => void
```

### batch

```ts
function 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.

```ts
import { atom, batch } from 'nanostores'

let $a = atom(0)
let $b = atom(0)

batch(() => {
  $a.set(1)
  $b.set(2)
})
```

#### Parameters

##### fn

() => `void`

Callback that performs the store writes.

#### Returns

`void`

## Store methods

### $store.get()

```ts
get(): Value;
```

Get store value.

In contrast with [ReadableAtom#value](/docs/api/#type-readableatom) this value will be always initialized even if store had no listeners.

```js
$store.get()
```

#### Returns

`Value`

Store value.

### $store.set()

```ts
set(newValue): void;
```

Change store value.

```js
$router.set({ path: location.pathname, page: parse(location.pathname) })
```

#### Parameters

#### newValue

`Value`

New store value.

#### Returns

`void`

### $store.setKey()

```ts
setKey<Key>(key, value): void;
```

Change key in store value.

```js
$settings.setKey('theme', 'dark')
```

To delete key set `undefined`.

```js
$settings.setKey('theme', undefined)
```

#### Type Parameters

#### Key

`Key` *extends* `string` | `number` | `symbol`

#### Parameters

#### key

`Key`

The key name.

#### value

`ValueWithUndefinedForIndexSignatures`<`Value`, `Key`>

New value.

#### Returns

`void`

### $store.listen()

```ts
listen(listener): () => void;
```

Subscribe to store changes.

In contrast with Store#subscribe it do not call listener immediately.

#### Parameters

#### listener

(`value`, `oldValue`) => `void`

Callback with store value and old value.

#### Returns

Function to remove listener.

() => `void`

### $store.subscribe()

```ts
subscribe(listener): () => void;
```

Subscribe to store changes and call listener immediately.

```plaintext
import { $router } from '../store'

$router.subscribe(page => {
  console.log(page)
})
```

#### Parameters

#### listener

(`value`, `oldValue?`) => `void`

Callback with store value and old value.

#### Returns

Function to remove listener.

() => `void`

## Lifecycle

### onMount

```ts
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`.

```js
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

##### Shared

`Shared` = `never`

#### Parameters

##### $store

[`Store`](/docs/api/#type-store)

Store to listen.

##### initialize

(`payload`) => `void` | (() => `void`)

Store constructor. Returns store destructor.

#### Returns

A function to remove constructor and destructor from store.

() => `void`

### STORE_UNMOUNT_DELAY

```ts
const STORE_UNMOUNT_DELAY: number;
```

## Map helpers

### listenKeys

```ts
function listenKeys<SomeStore>(
   $store,
   keys,
   listener
): () => void;
```

Listen for specific keys of the store.

In contrast with [subscribeKeys](/docs/api/#subscribekeys) it do not call listener immediately.

```js
import { listenKeys } from 'nanostores'

listenKeys($page, ['blocked'], (value, oldValue, changed) => {
  if (value.blocked) {
    console.log('You has no access')
  }
})
```

#### Type Parameters

##### SomeStore

`SomeStore` *extends* `object`

#### Parameters

##### $store

`SomeStore`

The store to listen.

##### keys

readonly [`MapStoreKeys`](/docs/api/#type-mapstorekeys)<`SomeStore`>\[]

The keys to listen.

##### listener

(`value`, `oldValue`, `changed`) => `void`

Standard listener.

#### Returns

() => `void`

### subscribeKeys

```ts
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.

```js
import { subscribeKeys } from 'nanostores'

subscribeKeys($page, ['blocked'], (value, oldValue, changed) => {
  if (value.blocked) {
    console.log('You has no access')
  }
})
```

#### Type Parameters

##### SomeStore

`SomeStore` *extends* `object`

#### Parameters

##### $store

`SomeStore`

The store to listen.

##### keys

readonly [`MapStoreKeys`](/docs/api/#type-mapstorekeys)<`SomeStore`>\[]

The keys to listen.

##### listener

(`value`, `oldValue`, `changed`) => `void`

Standard listener.

#### Returns

() => `void`

### setPath

```ts
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.

```plaintext
import { setPath } from 'nanostores'

setPath({ a: { b: { c: [] } } }, 'a.b.c[1]', 'hey')
// Returns `{ a: { b: { c: [<empty>, 'hey'] } } }`
```

#### Type Parameters

##### T

`T` *extends* [`BaseDeepMap`](/docs/api/#type-basedeepmap)

##### K

`K` *extends* `string`

#### Parameters

##### obj

`T`

Any object.

##### path

`K`

Path split by dots and `[]`. Like: `props.arr[1].nested`.

##### value

[`FromPath`](/docs/api/#type-frompath)<`T`, `K`>

#### Returns

`T`

The new object.

### getPath

```ts
function getPath<T, K>(obj, path): FromPath<T, K>;
```

Get a value by object path. `undefined` if key is missing.

```plaintext
import { getPath } from 'nanostores'

getPath({ a: { b: { c: ['hey', 'Hi!'] } } }, 'a.b.c[1]') // Returns 'Hi!'
```

#### Type Parameters

##### T

`T` *extends* [`BaseDeepMap`](/docs/api/#type-basedeepmap)

##### K

`K` *extends* `string`

#### Parameters

##### obj

`T`

Any object.

##### path

`K`

Path split by dots and `[]`. Like: `props.arr[1].nested`.

#### Returns

[`FromPath`](/docs/api/#type-frompath)<`T`, `K`>

The value for this path. Undefined if key is missing.

### setByKey

```ts
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.

```plaintext
import { setByKey } from 'nanostores'

setByKey({ a: { b: { c: [] } } }, ['a', 'b', 'c', 1], 'hey')
// Returns `{ a: { b: { c: [<empty>, 'hey'] } } }`
```

#### Type Parameters

##### T

`T` *extends* [`BaseDeepMap`](/docs/api/#type-basedeepmap)

#### Parameters

##### obj

`T`

Any object.

##### splittedKeys

`PropertyKey`\[]

An array of keys representing the path to the value.

##### value

`unknown`

New value.

#### Returns

`T`

The new object.

## Tasks & testing

### task

```ts
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.

```ts
import { task } from 'nanostores'

async function saveUser () {
  await task(async () => {
    await api.submit('/user', user.get())
    $user.setKey('saved', true)
  })
}
```

#### Type Parameters

##### Return

`Return` = `never`

#### Parameters

##### cb

() => `Return` | `Promise`<`Return`>

Async callback with task.

#### Returns

[`Task`](/docs/api/#type-task)<`Return`>

Return value from callback.

### startTask

```ts
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](/docs/api/#task).

```ts
import { startTask } from 'nanostores'

function saveUser () {
  const endTask = startTask()
  api.submit('/user', user.get(), () => {
    $user.setKey('saved', true)
    endTask()
  })
}
```

#### Returns

() => `void`

### allTasks

```ts
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.

```ts
import { allTasks } from 'nanostores'

it('saves user', async () => {
  saveUser()
  await allTasks()
  expect($user.get().saved).toBe(true)
})
```

#### Returns

`Promise`<`void`>

### cleanTasks

```ts
function cleanTasks(): void;
```

Forget all tracking tasks. Use it only for tests. [cleanStores](/docs/api/#cleanstores) cleans tasks automatically.

```js
import { cleanTasks } from 'nanostores'

afterEach(() => {
  cleanTasks()
})
```

#### Returns

`void`

### keepMount

```ts
function keepMount($store): void;
```

Prevent destructor call for the store.

Together with [cleanStores](/docs/api/#cleanstores) is useful tool for tests.

```js
import { keepMount } from 'nanostores'

keepMount($store)
```

#### Parameters

##### $store

\| [`Store`](/docs/api/#type-store) | [`MapCreator`](/docs/api/#type-mapcreator)<`any`, \[]>

The store.

#### Returns

`void`

### cleanStores

```ts
function cleanStores(...stores): void;
```

Destroys all cached stores and call

It also reset all tasks by calling [cleanTasks](/docs/api/#cleantasks).

```js
import { cleanStores } from 'nanostores'

afterEach(() => {
  cleanStores($router, $settings)
})
```

#### Parameters

##### stores

…( | [`MapCreator`](/docs/api/#type-mapcreator)<`any`, `any`\[]> | [`Store`](/docs/api/#type-store) | `undefined`)\[]

Used store classes.

#### Returns

`void`

Promise for stores destroying.

### clean

```ts
const clean: unique symbol;
```

## Advanced

### onStart

```ts
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](/docs/api/#onmount) to add constructor and destructor for the store.

You can communicate between listeners by `payload.shared`.

#### Type Parameters

##### Shared

`Shared` = `never`

#### Parameters

##### $store

[`Store`](/docs/api/#type-store)

The store to add listener.

##### listener

(`payload`) => `void`

Event callback.

#### Returns

A function to remove listener.

() => `void`

### onStop

```ts
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](/docs/api/#onmount) to add constructor and destructor for the store.

You can communicate between listeners by `payload.shared`.

#### Type Parameters

##### Shared

`Shared` = `never`

#### Parameters

##### $store

[`Store`](/docs/api/#type-store)

The store to add listener.

##### listener

(`payload`) => `void`

Event callback.

#### Returns

A function to remove listener.

() => `void`

### onSet

```ts
function onSet<Shared, SomeStore>($store, listener): () => void;
```

Add listener to store chagings.

```js
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

##### Shared

`Shared` = `never`

##### SomeStore

`SomeStore` *extends* [`Store`](/docs/api/#type-store) = [`Store`](/docs/api/#type-store)

#### Parameters

##### $store

`SomeStore`

The store to add listener.

##### listener

(`payload`) => `void`

Event callback.

#### Returns

A function to remove listener.

() => `void`

### onNotify

```ts
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

##### Shared

`Shared` = `never`

##### SomeStore

`SomeStore` *extends* [`Store`](/docs/api/#type-store) = [`Store`](/docs/api/#type-store)

#### Parameters

##### $store

`SomeStore`

The store to add listener.

##### listener

(`payload`) => `void`

Event callback.

#### Returns

A function to remove listener.

() => `void`

### mapCreator

```ts
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

##### Value

`Value` *extends* `object`

##### Args

`Args` *extends* `any`\[] = \[]

##### StoreExt

`StoreExt` *extends* `object` = `object`

#### Parameters

##### init?

(`store`, `id`, …`args`) => `void` | (() => `void`)

Store’s initializer. Returns store destructor.

#### Returns

[`MapCreator`](/docs/api/#type-mapcreator)<`Value`, `Args`>

### readonlyType

```ts
function readonlyType<Value>(store): ReadableAtom<Value>;
```

Change store type for readonly for export.

```ts
import { readonlyType } from 'nanostores'

const $storePrivate = atom(0)

export const $store = readonlyType($storePrivate)
```

#### Type Parameters

##### Value

`Value`

#### Parameters

##### store

[`ReadableAtom`](/docs/api/#type-readableatom)<`Value`>

The store to be exported.

#### Returns

[`ReadableAtom`](/docs/api/#type-readableatom)<`Value`>

The readonly store.

## Types

### ReadableAtom

Store object.

Type details

#### Extended by

* [`WritableAtom`](/docs/api/#type-writableatom)

#### Type Parameters

##### Value

`Value` = `any`

#### Properties

##### init

```ts
readonly init: Value | undefined;
```

Low-level attribute to read store’s initial value.

##### lc

```ts
readonly lc: number;
```

Listeners count.

##### value

```ts
readonly value: Value | undefined;
```

Low-level method to read store’s value without calling `onStart`.

Try to use only [ReadableAtom#get](/docs/api/#type-readableatom). Without subscribers, value can be undefined.

#### Methods

##### eq()

```ts
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

###### oldValue

`ReadonlyIfObject`<`Value`> | `undefined`

###### newValue

`ReadonlyIfObject`<`Value`>

###### Returns

`boolean`

`true` if the values are equal, `false` otherwise.

###### Remarks

Called only by the store’s own writes, so a store that never writes never calls it. `Map#setKey` uses [MapStore#eqKey](/docs/api/#type-mapstore) instead.

Before the first write, `oldValue` can be `undefined`, for instance on the first run of a computed store.

###### Default

```ts
Object.is
```

See [$store.get()](/docs/api/#store-get).

See [$store.listen()](/docs/api/#store-listen).

##### notify()

```ts
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

###### oldValue?

`ReadonlyIfObject`<`Value`>

###### Returns

`void`

##### off()

```ts
off(): void;
```

Unbind all listeners.

###### Returns

`void`

See [$store.subscribe()](/docs/api/#store-subscribe).

### WritableAtom

Store with a way to manually change the value.

Type details

#### Extends

* [`ReadableAtom`](/docs/api/#type-readableatom)<`Value`>

#### Extended by

* [`PreinitializedWritableAtom`](/docs/api/#type-preinitializedwritableatom)
* [`MapStore`](/docs/api/#type-mapstore)

#### Type Parameters

##### Value

`Value` = `any`

#### Properties

#### Methods

See [$store.set()](/docs/api/#store-set).

### MapStore

Store with a way to manually change the value.

Type details

#### Extends

* [`WritableAtom`](/docs/api/#type-writableatom)<`Value`>

#### Extended by

* [`PreinitializedMapStore`](/docs/api/#type-preinitializedmapstore)

#### Type Parameters

##### Value

`Value` *extends* `object` = `any`

#### Properties

#### Methods

##### eqKey()

```ts
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

###### Key

`Key` *extends* `string` | `number` | `symbol`

###### Parameters

###### oldValue

`Get`<`Value`, `Key`> | `undefined`

###### newValue

`Get`<`Value`, `Key`> | `undefined`

###### key

`Key`

###### Returns

`boolean`

`true` if the values are equal, `false` otherwise.

###### Remarks

Deleting an existing key skips the comparison and notifies either way. Whole-value writes use [ReadableAtom#eq](/docs/api/#type-readableatom) instead.

###### Default

```ts
Object.is
```

##### listen()

```ts
listen(listener): () => void;
```

Subscribe to store changes.

In contrast with Store#subscribe it do not call listener immediately.

###### Parameters

###### listener

(`value`, `oldValue`, `changedKey`) => `void`

Callback with store value and old value.

###### Returns

Function to remove listener.

() => `void`

###### Overrides

[`WritableAtom`](/docs/api/#type-writableatom).[`listen`](/docs/api/#type-writableatom)

##### notify()

```ts
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

###### oldValue?

`ReadonlyIfObject`<`Value`>

###### changedKey?

`AllKeys`<`Value`>

###### Returns

`void`

###### Overrides

[`WritableAtom`](/docs/api/#type-writableatom).[`notify`](/docs/api/#type-writableatom)

##### set()

```ts
set(newValue): void;
```

Change store value.

```js
$settings.set({ theme: 'dark' })
```

Operation is atomic, subscribers will be notified once with the new value. `changedKey` will be undefined

###### Parameters

###### newValue

`Value`

New store value.

###### Returns

`void`

###### Overrides

[`WritableAtom`](/docs/api/#type-writableatom).[`set`](/docs/api/#type-writableatom)

See [$store.setKey()](/docs/api/#store-setkey).

##### subscribe()

```ts
subscribe(listener): () => void;
```

Subscribe to store changes and call listener immediately.

```plaintext
import { $router } from '../store'

$router.subscribe(page => {
  console.log(page)
})
```

###### Parameters

###### listener

(`value`, `oldValue`, `changedKey`) => `void`

Callback with store value and old value.

###### Returns

Function to remove listener.

() => `void`

###### Overrides

[`WritableAtom`](/docs/api/#type-writableatom).[`subscribe`](/docs/api/#type-writableatom)

### Task

Type details

#### Extends

* `Promise`<`Value`>

#### Type Parameters

##### Value

`Value`

#### Properties

##### \[toStringTag]

```ts
readonly [toStringTag]: string;
```

###### Inherited from

```ts
Promise.[toStringTag]
```

##### t

```ts
t: true;
```

#### Methods

##### catch()

```ts
catch<TResult>(onrejected?): Promise<Value | TResult>;
```

Attaches a callback for only the rejection of the Promise.

###### Type Parameters

###### TResult

`TResult` = `never`

###### Parameters

###### onrejected?

((`reason`) => `TResult` | `PromiseLike`<`TResult`>) | `null`

The callback to execute when the Promise is rejected.

###### Returns

`Promise`<`Value` | `TResult`>

A Promise for the completion of the callback.

###### Inherited from

```ts
Promise.catch
```

##### finally()

```ts
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

###### onfinally?

(() => `void`) | `null`

The callback to execute when the Promise is settled (fulfilled or rejected).

###### Returns

`Promise`<`Value`>

A Promise for the completion of the callback.

###### Inherited from

```ts
Promise.finally
```

##### then()

```ts
then<TResult1, TResult2>(onfulfilled?, onrejected?): Promise<TResult1 | TResult2>;
```

Attaches callbacks for the resolution and/or rejection of the Promise.

###### Type Parameters

###### TResult1

`TResult1` = `Value`

###### TResult2

`TResult2` = `never`

###### Parameters

###### onfulfilled?

((`value`) => `TResult1` | `PromiseLike`<`TResult1`>) | `null`

The callback to execute when the Promise is resolved.

###### onrejected?

((`reason`) => `TResult2` | `PromiseLike`<`TResult2`>) | `null`

The callback to execute when the Promise is rejected.

###### Returns

`Promise`<`TResult1` | `TResult2`>

A Promise for the completion of which ever callback is executed.

###### Inherited from

```ts
Promise.then
```

### PreinitializedWritableAtom

Store with a way to manually change the value.

Type details

#### Extends

* [`WritableAtom`](/docs/api/#type-writableatom)<`Value`>

#### Type Parameters

##### Value

`Value`

#### Properties

##### value

```ts
readonly value: Value;
```

Low-level method to read store’s value without calling `onStart`.

Try to use only [ReadableAtom#get](/docs/api/#type-readableatom). Without subscribers, value can be undefined.

###### Overrides

[`WritableAtom`](/docs/api/#type-writableatom).[`value`](/docs/api/#type-writableatom)

#### Methods

### PreinitializedMapStore

Store with a way to manually change the value.

Type details

#### Extends

* [`MapStore`](/docs/api/#type-mapstore)<`Value`>

#### Type Parameters

##### Value

`Value` *extends* `object` = `any`

#### Properties

##### value

```ts
readonly value: Value;
```

Low-level method to read store’s value without calling `onStart`.

Try to use only [ReadableAtom#get](/docs/api/#type-readableatom). Without subscribers, value can be undefined.

###### Overrides

[`MapStore`](/docs/api/#type-mapstore).[`value`](/docs/api/#type-mapstore)

#### Methods

### MapCreator

Type details

#### Type Parameters

##### Value

`Value` *extends* `object` = `any`

##### Args

`Args` *extends* `any`\[] = \[]

```ts
MapCreator(id, ...args): MapStore<object & Value>;
```

#### Parameters

##### id

`string`

##### args

…`Args`

#### Returns

[`MapStore`](/docs/api/#type-mapstore)<`object` & `Value`>

#### Properties

##### cache

```ts
cache: object;
```

###### Index Signature

```ts
[id: string]: MapStore<object & Value>
```

#### Methods

##### build()

```ts
build(id, ...args): MapStore<object & Value>;
```

###### Parameters

###### id

`string`

###### args

…`Args`

###### Returns

[`MapStore`](/docs/api/#type-mapstore)<`object` & `Value`>

### Store

```ts
type Store<Value> =
  | ReadableAtom<Value>
| WritableStore<Value>;
```

Type details

#### Type Parameters

##### Value

`Value` = `any`

### WritableStore

```ts
type WritableStore<Value> =
  | Value extends object ? MapStore<Value> : never
| WritableAtom<Value>;
```

Type details

#### Type Parameters

##### Value

`Value` = `any`

### AnyStore

```ts
type AnyStore<Value> = Gettable<Value> & object;
```

Type details

#### Type Parameters

##### Value

`Value` = `any`

#### Type Declaration

##### value

```ts
readonly value: undefined | Value;
```

### Atom

```ts
type Atom<Value> =
  | ReadableAtom<Value>
| WritableAtom<Value>;
```

Type details

#### Type Parameters

##### Value

`Value` = `any`

### ListenableStore

```ts
type ListenableStore<Value> = Gettable<Value> & object;
```

Type details

#### Type Parameters

##### Value

`Value` = `any`

#### Type Declaration

##### listen()

```ts
listen(listener): () => void;
```

###### Parameters

###### listener

() => `void`

###### Returns

() => `void`

### Gettable

```ts
type Gettable<Value> = object;
```

Type details

#### Type Parameters

##### Value

`Value` = `any`

#### Methods

##### get()

```ts
get(): Value;
```

###### Returns

`Value`

### StoreValue

```ts
type StoreValue<SomeStore> = SomeStore extends Gettable<infer Value> ? Value : any;
```

Type details

#### Type Parameters

##### SomeStore

`SomeStore`

### StoreValues

```ts
type StoreValues<Stores> = { -readonly [Index in keyof Stores]: StoreValue<Stores[Index]> };
```

Type details

#### Type Parameters

##### Stores

`Stores` *extends* readonly [`Gettable`](/docs/api/#type-gettable)\[]

### MapStoreKeys

```ts
type MapStoreKeys<SomeStore> = SomeStore extends MapStore ? AllKeys<StoreValue<SomeStore>> : SomeStore extends object ? K : AllKeys<StoreValue<SomeStore>>;
```

Type details

#### Type Parameters

##### SomeStore

`SomeStore`

### DeepMapStore

```ts
type DeepMapStore<T> = object & Omit<WritableAtom<T>, "listen" | "notify" | "setKey" | "subscribe">;
```

Type details

#### Type Parameters

##### T

`T` *extends* [`BaseDeepMap`](/docs/api/#type-basedeepmap)

#### Type Declaration

##### setKey

```ts
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).

```js
$settings.setKey('visuals.theme', 'dark')
```

###### Type Parameters

###### K

`K` *extends* [`AllPaths`](/docs/api/#type-allpaths)<`T`>

###### Parameters

###### key

`K`

The key name. Attributes can be split with a dot `.` and `[]`.

###### value

`FromPathWithIndexSignatureUndefined`<`T`, `K`>

New value.

###### Returns

`void`

##### listen()

```ts
listen(listener): () => void;
```

Subscribe to store changes.

In contrast with Store#subscribe it do not call listener immediately.

###### Parameters

###### listener

(`value`, `oldValue`, `changedKey`) => `void`

Callback with store value and old value.

###### Returns

Function to remove listener.

() => `void`

##### notify()

```ts
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

###### oldValue?

`T`

###### changedKey?

[`AllPaths`](/docs/api/#type-allpaths)<`T`>

###### Returns

`void`

##### subscribe()

```ts
subscribe(listener): () => void;
```

Subscribe to store changes and call listener immediately.

```plaintext
import { $settings } from '../store'

$settings.subscribe(settings => {
  console.log(settings)
})
```

###### Parameters

###### listener

(`value`, `oldValue`, `changedKey`) => `void`

Callback with store value and old value.

###### Returns

Function to remove listener.

() => `void`

### BaseDeepMap

```ts
type BaseDeepMap = Record<string, unknown>;
```

### AllPaths

```ts
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

##### T

`T`

##### P

`P` *extends* `string` = `""`

##### MaxDepth

`MaxDepth` *extends* `number` = `10`

### FromPath

```ts
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;
```

Type details

#### Type Parameters

##### T

`T`

##### P

`P`

## Deprecated

### deepMap

```ts
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.

Use `@nanostores/deepmap`.

#### Type Parameters

##### T

`T` *extends* [`BaseDeepMap`](/docs/api/#type-basedeepmap)

#### Parameters

##### init?

`T`

Initialize store and return store destructor.

#### Returns

[`DeepMapStore`](/docs/api/#type-deepmapstore)<`T`>

The store object with methods to subscribe.

### getKey

```ts
function getKey<T, K>(store, key): FromPath<T, K>;
```

Use `@nanostores/deepmap`.

#### Type Parameters

##### T

`T` *extends* `Record`<`string`, `unknown`>

##### K

`K` *extends* `string`

#### Parameters

##### store

[`AnyStore`](/docs/api/#type-anystore)<`T`>

##### key

`K`

#### Returns

[`FromPath`](/docs/api/#type-frompath)<`T`, `K`>
