Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: hydrated for indexedDB #5356

Merged
merged 3 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion app/utils/indexedDB-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,20 @@ import { get, set, del, clear } from "idb-keyval";
class IndexedDBStorage implements StateStorage {
public async getItem(name: string): Promise<string | null> {
try {
return (await get(name)) || localStorage.getItem(name);
const value = (await get(name)) || localStorage.getItem(name);
return value;
} catch (error) {
return localStorage.getItem(name);
}
}

public async setItem(name: string, value: string): Promise<void> {
try {
const _value = JSON.parse(value);
if (!_value?.state?._hasHydrated) {
console.warn("skip setItem", name);
return;
}
await set(name, value);
} catch (error) {
localStorage.setItem(name, value);
Expand Down
12 changes: 12 additions & 0 deletions app/utils/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ type SecondParam<T> = T extends (

type MakeUpdater<T> = {
lastUpdateTime: number;
_hasHydrated: boolean;

markUpdate: () => void;
update: Updater<T>;
setHasHydrated: (state: boolean) => void;
};

type SetStoreState<T> = (
Expand All @@ -33,12 +35,19 @@ export function createPersistStore<T extends object, M>(
persistOptions: SecondParam<typeof persist<T & M & MakeUpdater<T>>>,
) {
persistOptions.storage = createJSONStorage(() => indexedDBStorage);
const oldOonRehydrateStorage = persistOptions?.onRehydrateStorage;
persistOptions.onRehydrateStorage = (state) => {
oldOonRehydrateStorage?.(state);
return () => state.setHasHydrated(true);
};

return create(
persist(
combine(
{
...state,
lastUpdateTime: 0,
_hasHydrated: false,
},
(set, get) => {
return {
Expand All @@ -57,6 +66,9 @@ export function createPersistStore<T extends object, M>(
lastUpdateTime: Date.now(),
});
},
setHasHydrated: (state: boolean) => {
set({ _hasHydrated: state } as Partial<T & M & MakeUpdater<T>>);
},
} as M & MakeUpdater<T>;
},
),
Expand Down
Loading