Restore recent environment on workspace change

Fixes #6
This commit is contained in:
Gregory Schier
2023-10-29 11:31:13 -07:00
parent 7dac299edd
commit 9dd4489049
4 changed files with 40 additions and 19 deletions

View File

@@ -1,31 +1,38 @@
import { useEffect } from 'react';
import { createGlobalState, useEffectOnce, useLocalStorage } from 'react-use';
import { useActiveRequestId } from './useActiveRequestId';
import { createGlobalState, useEffectOnce } from 'react-use';
import { useActiveWorkspaceId } from './useActiveWorkspaceId';
import { useActiveEnvironmentId } from './useActiveEnvironmentId';
import { useKeyValue } from './useKeyValue';
import { NAMESPACE_GLOBAL, getKeyValue } from '../lib/keyValueStore';
const useHistoryState = createGlobalState<string[]>([]);
const kvKey = (workspaceId: string) => 'recent_environments::' + workspaceId;
const namespace = NAMESPACE_GLOBAL;
const defaultValue: string[] = [];
export function useRecentEnvironments() {
const activeWorkspaceId = useActiveWorkspaceId();
const activeEnvironmentId = useActiveEnvironmentId();
const [history, setHistory] = useHistoryState();
const [lsState, setLSState] = useLocalStorage<string[]>(
'recent_environments::' + activeWorkspaceId,
[],
);
const kv = useKeyValue<string[]>({
key: kvKey(activeWorkspaceId ?? 'n/a'),
namespace,
defaultValue,
});
// Load local storage state on initial render
useEffectOnce(() => {
if (lsState) {
setHistory(lsState);
if (kv.value) {
setHistory(kv.value);
}
});
// Update local storage state when history changes
useEffect(() => {
setLSState(history);
}, [history, setLSState]);
kv.set(history);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [history]);
// Set history when active request changes
useEffect(() => {
@@ -38,3 +45,11 @@ export function useRecentEnvironments() {
return history;
}
export async function getRecentEnvironments(workspaceId: string) {
return getKeyValue<string[]>({
namespace,
key: kvKey(workspaceId),
fallback: defaultValue,
});
}