Skip to content

Commit

Permalink
Merge pull request ChatGPTNextWeb#5356 from ConnectAI-E/feature/indexdb
Browse files Browse the repository at this point in the history
fix: hydrated for indexedDB
  • Loading branch information
lloydzhou authored Sep 4, 2024
2 parents 97a4a91 + 53dcae9 commit 8570457
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
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

0 comments on commit 8570457

Please sign in to comment.