Skip to content
Source
Sign inSign up
TanStack/store

feat: add state persistence support #246

Closedahmdtalat(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/246/headopened

Features

  • Local storage support out of the box
  • Custom storage adapter support
  • Custom serialization/deserialization
  • Manual persistence controls (persist, rehydrate, clear)
  • Full TypeScript support
    1. we already have a separate TanStack Persister project that I started 6 months ago. It may be best to keep that stuff separate. I would hope that we would need minimal changes to the core store package to interact with persister.

    2. slargat(GitHub profile, opens in a new tab)commented

      @ahmdtalat @KevinVandy Can this be a solution ?

      type PersistedStoreOptions<TState, TSelected extends Partial<TState> = TState> =
      	| {
      		key: string
      		version?: string
      		defaultState: TState
      		schema: StandardSchemaV1<any, TSelected>
      		storage?: Storage
      		serialize?: never
      		deserialize?: never
      	}
      	| {
      		key: string
      		version?: string
      		defaultState: TState
      		schema?: never
      		serialize: (state?: TState) => PersistedStorage<TSelected>
      		deserialize: (stored: string) => TSelected
      		storage?: Storage
      	}
      
      export class PersistedStore<T> {
      	public readonly persister: StoragePersister<T>
      	public readonly store: Store<T>
      	private readonly persistEffect: Effect
      	private readonly _unmount: () => void
      
      	constructor(options: PersistedStoreOptions<T>) {
      		// Enforce mutual exclusivity at runtime
      		const hasSchema = !!options.schema
      		const hasCustomSerDes = !!options.serialize && !!options.deserialize
      
      		if (hasSchema && hasCustomSerDes) {
      			throw new Error("Provide either 'schema' or both 'serialize' and 'deserialize', not both.")
      		}
      		if (!hasSchema && !hasCustomSerDes) {
      			throw new Error("You must provide either 'schema' or both 'serialize' and 'deserialize'.")
      		}
      
      		// Choose serializer/deserializer logic
      		// let serializer: (args: { state: T, buster?: string, timestamp?: number }) => string
      		let serializer: StoragePersisterOptions<T, T>["serializer"]
      		// let deserializer: (stored: string) => { state: T, buster?: string, timestamp?: number }
      		let deserializer: StoragePersisterOptions<T, T>["deserializer"]
      
      		if (hasSchema) {
      			const isValid = (state?: T) => options.schema!["~standard"]!.validate(state)
      			serializer = ({ state, buster, timestamp }) => {
      				return JSON.stringify({
      					state: isValid(state) ? state : options.defaultState,
      					buster,
      					timestamp
      				})
      			}
      			deserializer = (stored) => {
      				try {
      					const parsed = JSON.parse(stored)
      					const stateData = parsed.state ?? parsed
      					return {
      						state: isValid(stateData) ? stateData : options.defaultState,
      						buster: parsed.buster,
      						timestamp: parsed.timestamp ?? Date.now()
      					}
      				} catch {
      					return { state: options.defaultState, timestamp: Date.now() }
      				}
      			}
      		} else {
      			// Custom serialize/deserialize
      			serializer = ({ state, buster, timestamp }) => {
      				const persisted = options.serialize!(state)
      				return JSON.stringify({ ...persisted, buster, timestamp })
      			}
      			deserializer = (stored) => {
      				try {
      					const parsed = JSON.parse(stored)
      					const stateData = options.deserialize!(stored)
      					return {
      						state: stateData,
      						buster: parsed.buster,
      						timestamp: parsed.timestamp ?? Date.now()
      					}
      				} catch {
      					return { state: options.defaultState, timestamp: Date.now() }
      				}
      			}
      		}
      
      		this.persister = new StoragePersister<T>({
      			key: options.key,
      			buster: options.version ?? "v1",
      			defaultState: options.defaultState,
      			serializer,
      			deserializer,
      			storage: options?.storage ?? window.localStorage
      		})
      
      		this.store = new Store<T>(this.persister.loadState() ?? options.defaultState)
      
      		this.persistEffect = new Effect({
      			fn: () => this.persister.saveState(this.store.state),
      			deps: [this.store],
      			eager: false
      		})
      
      		this._unmount = this.persistEffect.mount()
      	}
      
      	unmount() {
      		this._unmount()
      	}
      }

      Adaptation of the useStore hook

      /**
       * @private
       */
      export type NoInfer<T> = [T][T extends any ? 0 : never]
      type EqualityFn<T> = (objA: T, objB: T) => boolean
      interface UseStoreOptions<T> {
      	equal?: EqualityFn<T>
      }
      
      // Overloads to accept Store, Derived, or PersistedStore
      export function useStore<TState, TSelected = NoInfer<TState>>(
      	store: Store<TState, any> | Derived<TState, any> | PersistedStore<TState>,
      	selector?: (state: NoInfer<TState>) => TSelected,
      	options?: UseStoreOptions<TSelected>
      ): TSelected
      
      /**
       * Accepts a TanStack Store, Derived, or PersistedStore instance.
       * If a PersistedStore is provided, uses its underlying Store for subscription.
       */
      export function useStore<TState, TSelected = NoInfer<TState>>(
      	store: Store<TState, any> | Derived<TState, any> | PersistedStore<TState>,
      	selector: (state: NoInfer<TState>) => TSelected = d => d as any,
      	options: UseStoreOptions<TSelected> = {}
      ): TSelected {
      	// Type guard for PersistedStore
      	const isPersistedStore = (s: any): s is PersistedStore<TState> =>
      		s && typeof s === "object" && "store" in s && s.store instanceof Store
      
      	const baseStore = isPersistedStore(store) ? store.store : store
      	const equal = options.equal ?? shallow
      	const slice = useSyncExternalStoreWithSelector(
      		baseStore.subscribe,
      		() => baseStore.state,
      		() => baseStore.state,
      		selector,
      		equal
      	)
      	return slice
      }
      
      export function shallow<T>(objA: T, objB: T) {
      	if (Object.is(objA, objB)) {
      		return true
      	}
      
      	if (
      		typeof objA !== "object"
      		|| objA === null
      		|| typeof objB !== "object"
      		|| objB === null
      	) {
      		return false
      	}
      
      	if (objA instanceof Map && objB instanceof Map) {
      		if (objA.size !== objB.size)
      			return false
      		for (const [k, v] of objA) {
      			if (!objB.has(k) || !Object.is(v, objB.get(k)))
      				return false
      		}
      		return true
      	}
      
      	if (objA instanceof Set && objB instanceof Set) {
      		if (objA.size !== objB.size)
      			return false
      		for (const v of objA) {
      			if (!objB.has(v))
      				return false
      		}
      		return true
      	}
      
      	if (objA instanceof Date && objB instanceof Date) {
      		if (objA.getTime() !== objB.getTime())
      			return false
      		return true
      	}
      
      	const keysA = getOwnKeys(objA)
      	if (keysA.length !== getOwnKeys(objB).length) {
      		return false
      	}
      
      	for (let i = 0; i < keysA.length; i++) {
      		if (
      			!Object.prototype.hasOwnProperty.call(objB, keysA[i] as string)
      			|| !Object.is(objA[keysA[i] as keyof T], objB[keysA[i] as keyof T])
      		) {
      			return false
      		}
      	}
      	return true
      }
      
      function getOwnKeys(obj: object): Array<string | symbol> {
      	return (Object.keys(obj) as Array<string | symbol>).concat(
      		Object.getOwnPropertySymbols(obj)
      	)
      }
      
    3. KevinVandy closed this

Sign in to join this conversation.