Last active
January 12, 2023 23:11
-
-
Save kinoadr/9766a45293ac9102471d96f218bd5eaa to your computer and use it in GitHub Desktop.
Zustand (^3.7.0) persist middleware with deferred hydration.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { persist, PersistOptions } from 'zustand/middleware'; | |
import { GetState, SetState, StoreApi } from 'zustand/vanilla'; | |
type DeferredPersistOptions<S extends object> = PersistOptions<S, Partial<S>> & { | |
hydrateOnResolve?: Promise<void>; | |
}; | |
const DEFAULT_GET_STORAGE = () => localStorage; | |
export default function deferredPersist< | |
S extends object, | |
CustomSetState extends SetState<S> = SetState<S>, | |
CustomGetState extends GetState<S> = GetState<S>, | |
CustomStoreApi extends StoreApi<S> = StoreApi<S>, | |
>( | |
config: (set: CustomSetState, get: CustomGetState, api: CustomStoreApi) => S, | |
deferredOptions: DeferredPersistOptions<S>, | |
) { | |
const hydrateOnResolve = deferredOptions.hydrateOnResolve || Promise.resolve(); | |
const getStorage = deferredOptions.getStorage || DEFAULT_GET_STORAGE; | |
const options: PersistOptions<S> = { | |
...deferredOptions, | |
getStorage: () => ({ | |
setItem: async (...args) => hydrateOnResolve.then(() => getStorage().setItem(...args)), | |
getItem: async (...args) => hydrateOnResolve.then(() => getStorage().getItem(...args)), | |
removeItem: async (...args) => hydrateOnResolve.then(() => getStorage().removeItem?.(...args)), | |
}), | |
}; | |
return persist<S, CustomSetState, CustomGetState, CustomStoreApi>(config, options); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@PAXANDDOS This was implemented to work with zustand
^3.7.0
. Maybe you should consider downgrading from4.0.0
to this version ?