Skip to content
Myr

persist.ts

This file

Path

src/middleware/persist.ts

403 lines · 11.7 KiB · TypeScript

Last changed by

fix(persist): clearStorage() should invalidate concurrent async rehydration (#3555)Copilotbefore adoption3febf8c

History of this file

Take it

1import type {2  StateCreator,3  StoreApi,4  StoreMutatorIdentifier,5} from '../vanilla.ts'67export interface StateStorage<R = unknown> {8  getItem: (name: string) => string | null | Promise<string | null>9  setItem: (name: string, value: string) => R10  removeItem: (name: string) => R11}1213export type StorageValue<S> = {14  state: S15  version?: number16}1718export interface PersistStorage<S, R = unknown> {19  getItem: (20    name: string,21  ) => StorageValue<S> | null | Promise<StorageValue<S> | null>22  setItem: (name: string, value: StorageValue<S>) => R23  removeItem: (name: string) => R24}2526type JsonStorageOptions = {27  reviver?: (key: string, value: unknown) => unknown28  replacer?: (key: string, value: unknown) => unknown29}3031export function createJSONStorage<S, R = unknown>(32  getStorage: () => StateStorage<R>,33  options?: JsonStorageOptions,34): PersistStorage<S, unknown> | undefined {35  let storage: StateStorage<R> | undefined36  try {37    storage = getStorage()38  } catch {39    // prevent error if the storage is not defined (e.g. when server side rendering a page)40    return41  }42  const persistStorage: PersistStorage<S, R> = {43    getItem: (name) => {44      const parse = (str: string | null) => {45        if (str === null) {46          return null47        }48        return JSON.parse(str, options?.reviver) as StorageValue<S>49      }50      const str = storage.getItem(name) ?? null51      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 persistStorage61}6263export interface PersistOptions<64  S,65  PersistedState = S,66  PersistReturn = unknown,67> {68  /** Name of the storage (must be unique) */69  name: string70  /**71   * Use a custom persist storage.72   *73   * Combining `createJSONStorage` helps creating a persist storage74   * with JSON.parse and JSON.stringify.75   *76   * @default createJSONStorage(() => window.localStorage)77   */78  storage?: PersistStorage<PersistedState, PersistReturn> | undefined79  /**80   * Filter the persisted value.81   *82   * @params state The state's value83   */84  partialize?: (state: S) => PersistedState85  /**86   * A function returning another (optional) function.87   * The main function will be called before the state rehydration.88   * The returned function will be called after the state rehydration or when an error occurred.89   */90  onRehydrateStorage?: (91    state: S,92  ) => ((state?: S, error?: unknown) => void) | void93  /**94   * If the stored state's version mismatch the one specified here, the storage will not be used.95   * This is useful when adding a breaking change to your store.96   */97  version?: number98  /**99   * A function to perform persisted state migration.100   * This function will be called when persisted state versions mismatch with the one specified here.101   */102  migrate?: (103    persistedState: unknown,104    version: number,105  ) => PersistedState | Promise<PersistedState>106  /**107   * A function to perform custom hydration merges when combining the stored state with the current one.108   * By default, this function does a shallow merge.109   */110  merge?: (persistedState: unknown, currentState: S) => S111112  /**113   * An optional boolean that will prevent the persist middleware from triggering hydration on initialization,114   * This allows you to call `rehydrate()` at a specific point in your apps rendering life-cycle.115   *116   * This is useful in SSR application.117   *118   * @default false119   */120  skipHydration?: boolean121}122123type PersistListener<S> = (state: S) => void124125type StorePersist<S, Ps, Pr> = S extends {126  getState: () => infer T127  setState: {128    // capture both overloads of setState129    (...args: infer Sa1): infer Sr1130    (...args: infer Sa2): infer Sr2131  }132}133  ? {134      setState(...args: Sa1): Sr1 | Pr135      setState(...args: Sa2): Sr2 | Pr136      persist: {137        setOptions: (options: Partial<PersistOptions<T, Ps, Pr>>) => void138        clearStorage: () => void139        rehydrate: () => Promise<void> | void140        hasHydrated: () => boolean141        onHydrate: (fn: PersistListener<T>) => () => void142        onFinishHydration: (fn: PersistListener<T>) => () => void143        getOptions: () => Partial<PersistOptions<T, Ps, Pr>>144      }145    }146  : never147148type Thenable<Value> = {149  then<V>(150    onFulfilled: (value: Value) => V | Promise<V> | Thenable<V>,151  ): Thenable<V>152  catch<V>(153    onRejected: (reason: Error) => V | Promise<V> | Thenable<V>,154  ): Thenable<V>155}156157const toThenable =158  <Result, Input>(159    fn: (input: Input) => Result | Promise<Result> | Thenable<Result>,160  ) =>161  (input: Input): Thenable<Result> => {162    try {163      const result = fn(input)164      if (result instanceof Promise) {165        return result as Thenable<Result>166      }167      return {168        then(onFulfilled) {169          return toThenable(onFulfilled)(result as Result)170        },171        catch(_onRejected) {172          return this as Thenable<any>173        },174      }175    } catch (e: any) {176      return {177        then(_onFulfilled) {178          return this as Thenable<any>179        },180        catch(onRejected) {181          return toThenable(onRejected)(e)182        },183      }184    }185  }186187const persistImpl: PersistImpl = (config, baseOptions) => (set, get, api) => {188  type S = ReturnType<typeof config>189  let options = {190    storage: createJSONStorage<S, void>(() => window.localStorage),191    partialize: (state: S) => state,192    version: 0,193    merge: (persistedState: unknown, currentState: S) => ({194      ...currentState,195      ...(persistedState as object),196    }),197    ...baseOptions,198  }199200  let hasHydrated = false201  // Counter to track hydration versions and prevent race conditions202  // when multiple rehydrate() calls happen concurrently203  let hydrationVersion = 0204  const hydrationListeners = new Set<PersistListener<S>>()205  const finishHydrationListeners = new Set<PersistListener<S>>()206  let storage = options.storage207208  if (!storage) {209    return config(210      (...args) => {211        console.warn(212          `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`,213        )214        set(...(args as Parameters<typeof set>))215      },216      get,217      api,218    )219  }220221  const setItem = () => {222    const state = options.partialize({ ...get() })223    return (storage as PersistStorage<S, unknown>).setItem(options.name, {224      state,225      version: options.version,226    })227  }228229  const savedSetState = api.setState230231  api.setState = (state, replace) => {232    savedSetState(state, replace as any)233    return setItem()234  }235236  const configResult = config(237    (...args) => {238      set(...(args as Parameters<typeof set>))239      return setItem()240    },241    get,242    api,243  )244245  api.getInitialState = () => configResult246247  // a workaround to solve the issue of not storing rehydrated state in sync storage248  // the set(state) value would be later overridden with initial state by create()249  // to avoid this, we merge the state from localStorage into the initial state.250  let stateFromStorage: S | undefined251252  // rehydrate initial state with existing stored state253  const hydrate = () => {254    if (!storage) return255256    // On the first invocation of 'hydrate', state will not yet be defined (this is257    // true for both the 'asynchronous' and 'synchronous' case). Pass 'configResult'258    // as a backup  to 'get()' so listeners and 'onRehydrateStorage' are called with259    // the latest available state.260261    // Increment version to invalidate any in-flight hydration262    const currentVersion = ++hydrationVersion263    hasHydrated = false264    hydrationListeners.forEach((cb) => cb(get() ?? configResult))265266    const postRehydrationCallback =267      options.onRehydrateStorage?.(get() ?? configResult) || undefined268269    // bind is used to avoid `TypeError: Illegal invocation` error270    return toThenable(storage.getItem.bind(storage))(options.name)271      .then((deserializedStorageValue) => {272        if (deserializedStorageValue) {273          if (274            typeof deserializedStorageValue.version === 'number' &&275            deserializedStorageValue.version !== options.version276          ) {277            if (options.migrate) {278              const migration = options.migrate(279                deserializedStorageValue.state,280                deserializedStorageValue.version,281              )282              if (migration instanceof Promise) {283                return migration.then((result) => [true, result] as const)284              }285              return [true, migration] as const286            }287            console.error(288              `State loaded from storage couldn't be migrated since no migrate function was provided`,289            )290          } else {291            return [false, deserializedStorageValue.state] as const292          }293        }294        return [false, undefined] as const295      })296      .then((migrationResult) => {297        // Abort if a newer hydration has started298        if (currentVersion !== hydrationVersion) {299          return300        }301        const [migrated, migratedState] = migrationResult302        stateFromStorage = options.merge(303          migratedState as S,304          get() ?? configResult,305        )306307        set(stateFromStorage as S, true)308        if (migrated) {309          return setItem()310        }311      })312      .then(() => {313        // Abort if a newer hydration has started314        if (currentVersion !== hydrationVersion) {315          return316        }317        postRehydrationCallback?.(get(), undefined)318319        // It's possible that 'postRehydrationCallback' updated the state. To ensure320        // that isn't overwritten when returning 'stateFromStorage' below321        // (synchronous-case only), update 'stateFromStorage' to point to the latest322        // state. In the asynchronous case, 'stateFromStorage' isn't used after this323        // callback, so there's no harm in updating it to match the latest state.324        stateFromStorage = get()325        hasHydrated = true326        finishHydrationListeners.forEach((cb) => cb(stateFromStorage as S))327      })328      .catch((e: Error) => {329        // Abort if a newer hydration has started330        if (currentVersion !== hydrationVersion) {331          return332        }333        postRehydrationCallback?.(undefined, e)334      })335  }336337  ;(api as StoreApi<S> & StorePersist<StoreApi<S>, S, unknown>).persist = {338    setOptions: (newOptions) => {339      options = {340        ...options,341        ...newOptions,342      }343344      if (newOptions.storage) {345        storage = newOptions.storage346      }347    },348    clearStorage: () => {349      ++hydrationVersion350      storage?.removeItem(options.name)351    },352    getOptions: () => options,353    rehydrate: () => hydrate() as Promise<void>,354    hasHydrated: () => hasHydrated,355    onHydrate: (cb) => {356      hydrationListeners.add(cb)357358      return () => {359        hydrationListeners.delete(cb)360      }361    },362    onFinishHydration: (cb) => {363      finishHydrationListeners.add(cb)364365      return () => {366        finishHydrationListeners.delete(cb)367      }368    },369  }370371  if (!options.skipHydration) {372    hydrate()373  }374375  return stateFromStorage || configResult376}377378type Persist = <379  T,380  Mps extends [StoreMutatorIdentifier, unknown][] = [],381  Mcs extends [StoreMutatorIdentifier, unknown][] = [],382  U = T,383>(384  initializer: StateCreator<T, [...Mps, ['zustand/persist', unknown]], Mcs>,385  options: PersistOptions<T, U>,386) => StateCreator<T, Mps, [['zustand/persist', U], ...Mcs]>387388declare module '../vanilla' {389  interface StoreMutators<S, A> {390    'zustand/persist': WithPersist<S, A>391  }392}393394type Write<T, U> = Omit<T, keyof U> & U395396type WithPersist<S, A> = Write<S, StorePersist<S, A, unknown>>397398type PersistImpl = <T>(399  storeInitializer: StateCreator<T, [], []>,400  options: PersistOptions<T, T>,401) => StateCreator<T, [], []>402403export const persist = persistImpl as unknown as Persist