MCPcopy
hub / github.com/pmndrs/zustand / createJSONStorage

Function createJSONStorage

src/middleware/persist.ts:31–61  ·  view source on GitHub ↗
(
  getStorage: () => StateStorage<R>,
  options?: JsonStorageOptions,
)

Source from the content-addressed store, hash-verified

29}
30
31export function createJSONStorage<S, R = unknown>(
32 getStorage: () => StateStorage<R>,
33 options?: JsonStorageOptions,
34): PersistStorage<S, unknown> | undefined {
35 let storage: StateStorage<R> | undefined
36 try {
37 storage = getStorage()
38 } catch {
39 // prevent error if the storage is not defined (e.g. when server side rendering a page)
40 return
41 }
42 const persistStorage: PersistStorage<S, R> = {
43 getItem: (name) => {
44 const parse = (str: string | null) => {
45 if (str === null) {
46 return null
47 }
48 return JSON.parse(str, options?.reviver) as StorageValue<S>
49 }
50 const str = storage.getItem(name) ?? null
51 if (str instanceof Promise) {
52 return str.then(parse)
53 }
54 return parse(str)
55 },
56 setItem: (name, newValue) =>
57 storage.setItem(name, JSON.stringify(newValue, options?.replacer)),
58 removeItem: (name) => storage.removeItem(name),
59 }
60 return persistStorage
61}
62
63export interface PersistOptions<
64 S,

Callers 5

createStoreFunction · 0.90
createStoreFunction · 0.90
persistImplFunction · 0.85

Calls 1

parseFunction · 0.85

Tested by 2

createStoreFunction · 0.72
createStoreFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…