( getStorage: () => StateStorage<R>, options?: JsonStorageOptions, )
| 29 | } |
| 30 | |
| 31 | export 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 | |
| 63 | export interface PersistOptions< |
| 64 | S, |
searching dependent graphs…