Refactor recentRequest/Env/Workspace

This commit is contained in:
Gregory Schier
2024-02-15 15:14:18 -08:00
parent b7d9f0bf92
commit c8feb6482b
4 changed files with 23 additions and 75 deletions

View File

@@ -1,12 +1,9 @@
import { useEffect, useMemo } from 'react';
import { createGlobalState, useEffectOnce } from 'react-use';
import { getKeyValue, NAMESPACE_GLOBAL } from '../lib/keyValueStore';
import { useActiveWorkspaceId } from './useActiveWorkspaceId';
import { useKeyValue } from './useKeyValue';
import { useWorkspaces } from './useWorkspaces';
const useHistoryState = createGlobalState<string[]>([]);
const kvKey = () => 'recent_workspaces';
const namespace = NAMESPACE_GLOBAL;
const defaultValue: string[] = [];
@@ -14,38 +11,25 @@ const defaultValue: string[] = [];
export function useRecentWorkspaces() {
const workspaces = useWorkspaces();
const activeWorkspaceId = useActiveWorkspaceId();
const [history, setHistory] = useHistoryState();
const kv = useKeyValue<string[]>({
key: kvKey(),
namespace,
defaultValue,
});
// Load local storage state on initial render
useEffectOnce(() => {
if (kv.value) {
setHistory(kv.value);
}
});
// Update local storage state when history changes
useEffect(() => {
kv.set(history);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [history]);
// Set history when active request changes
useEffect(() => {
setHistory((currentHistory: string[]) => {
kv.set((currentHistory: string[]) => {
if (activeWorkspaceId === null) return currentHistory;
const withoutCurrent = currentHistory.filter((id) => id !== activeWorkspaceId);
return [activeWorkspaceId, ...withoutCurrent];
});
}, [activeWorkspaceId, setHistory]);
}).catch(console.error);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onlyValidIds = useMemo(
() => history.filter((id) => workspaces.some((w) => w.id === id)),
[history, workspaces],
() => kv.value?.filter((id) => workspaces.some((w) => w.id === id)) ?? [],
[kv.value, workspaces],
);
return onlyValidIds;