百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
P

persistent

> 编程语言
开源

适用于 Nano Stores 状态管理器的智能商店,用于在 localStorage 中保存数据

379 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

适用于 Nano Stores 状态管理器的智能商店,用于在 localStorage 中保存数据

Nano Stores Persistent

A smart store for Nano Stores state manager to keep data in localStorage and synchronize changes between browser tabs.

  • Small. From 296 bytes (minified and brotlied). Zero dependencies. It uses Size Limit to control size.
  • It has good TypeScript.
  • Framework agnostic. It supports SSR. localStorage can be switched to another storage.
typescript
import { persistentAtom } from '@nanostores/persistent'

export const $locale = persistentAtom('locale', 'en')

  Nano Stores Persistent is built by Evil Martians, an American design and engineering consultancy for developer tools, AI, and cybersecurity startups.


Install

bash
npm install nanostores @nanostores/persistent

Usage

See Nano Stores docs about using the store and subscribing to store’s changes in UI frameworks.

Primitive Store

The store with primitive value keeps the whole data in the single localStorage key.

typescript
import { persistentAtom } from '@nanostores/persistent'

export const $shoppingCart = persistentAtom('cart', [], {
  encode: JSON.stringify,
  decode: JSON.parse
})

This store will keep its value in cart key oflocalStorage. An empty array [] will be initial value on missed key in localStorage.

You can change store value by set method.

typescript
$shoppingCart.set([...$shoppingCart.get(), newProduct])

You can store the object in a primitive store too. But Persistent Map store is better, because map store will update value if you add a new key to the initial value.

There is simple wrapper to store boolean:

typescript
import { persistentBoolean } from '@nanostores/persistent'

export const $reduceMotion = persistentBoolean('reduce-motion')

JSON Store

persistentJSON is a handy shortcut for persistentAtom that takes care of JSON serialization for you.

It works with any valid JSON type: objects, arrays, primitives (string, number, boolean, null).

typescript
import { persistentJSON } from '@nanostores/persistent'

const $cart = persistentJSON('cart', [])
const $theme = persistentJSON('theme', 'auto')

$cart.set([...$cart.get(), newProduct])
$theme.set('dark')

You can omit initial value argument. In this case, we will add null to store type.

typescript
const $comments = persistentJSON('comments')

console.log($comments.get()?.map(i => i.userId)) // Safe access

Map Store

There is a special key-value map store. It will keep each key in separated localStorage key.

typescript
import { persistentMap } from '@nanostores/persistent'

export type SettingsValue = {
  sidebar: 'show' | 'hide'
  theme: 'dark' | 'light' | 'auto'
}

export const $settings = persistentMap('settings:', {
  sidebar: 'show',
  theme: 'auto'
})

This store will keep value in settings:sidebar and settings:theme keys.

You can change the key by setKey method:

typescript
$settings.setKey('sidebar', 'hide')

Sync between Browser Tabs

By default, the store changes will be synchronized between browser tabs.

There is a listen option to disable synchronization.

typescript
import { persistentAtom } from '@nanostores/persistent'

export const $draft = persistentAtom('draft', '', { listen: false })

Value Encoding

encode and decode options can be set to process a value before setting or after getting it from the persistent storage.

typescript
import { persistentAtom } from '@nanostores/persistent'

export const $draft = persistentAtom('draft', [], {
  encode(value) {
    return JSON.stringify(value)
  },
  decode(value) {
    try {
      return JSON.parse(value)
    } catch() {
      return value
    }
  }
})

Server-Side Rendering

The store has built-in SSR support. On the server, they will use empty objects instead of localStorage.

You can manually initialize stores with specific data:

javascript
if (isServer) {
  $locale.set(user.locale)
}

Persistent Engines

You can switch localStorage to any other storage for all used stores.

…

You do not need to do anything for server-side rendering. It's supported by default.

You need to specify bodies of events.addEventListener and events.removeEventListener only for environments with browser tabs or another reasons for storage synchronization.

perKey makes PersistentMap add one listener for each of its keys in addition to the one for all keys. This is relevant when events for key changes are only dispatched for keys that were specifically subscribed too.

For TypeScript, we have PersistentListener and PersistentEvent types for events object.

typescript
import { PersistentListener, PersistentEvent } from '@nanostores/persistent'

const events = {
  addEventListener(key: string, callback: PersistentListener) {
    …
  },
  removeEventListener(key: string, callback: PersistentListener) {
    …
  }
}

function onChange() {
  const event: PersistentEvent = {
    key: 'locale' // Changed storage key
    newValue: 'ru'
  }
  …
}

Tests

There is a special API to replace localStorage to a fake storage engine with helpers to change key and get all values.

javascript
import {
  useTestStorageEngine,
  setTestStorageKey,
  cleanTestStorage,
  getTestStorage
} from '@nanostores/persistent'

import { $settings } from './storage.js'

beforeAll(() => {
  useTestStorageEngine()
})

afterEach(() => {
  cleanTestStorage()
})

it('listens for changes', () => {
  setTestStorageKey('settings:locale', 'ru')
  expect($settings.get()).toEqual({ locale: 'ru' })
})

it('changes storage', () => {
  $settings.setKey('locale')
  expect(getTestStorage()).toEqual({ 'settings:locale': 'ru' })
})

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言