mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-22 19:30:15 +01:00
* feat: Update MCP package version and dependencies; refactor ToolContentPart type * refactor: Change module type to commonjs and update rollup configuration, remove unused dev dependency * refactor: Change async calls to synchronous for MCP and FlowStateManager retrieval * chore: Add eslint disable comment for i18next rule in DropdownPopup component * fix: improve statefulness of mcp servers selected if some were removed since last session * feat: implement conversation storage cleanup functions and integrate them into mutation success handlers * feat: enhance storage condition logic in useLocalStorageAlt to prevent unnecessary local storage writes * refactor: streamline local storage update logic in useLocalStorageAlt
69 lines
1.8 KiB
TypeScript
69 lines
1.8 KiB
TypeScript
/* `useLocalStorage`
|
|
*
|
|
* Features:
|
|
* - JSON Serializing
|
|
* - Also value will be updated everywhere, when value updated (via `storage` event)
|
|
*/
|
|
|
|
import { useEffect, useState } from 'react';
|
|
|
|
export default function useLocalStorage<T>(
|
|
key: string,
|
|
defaultValue: T,
|
|
globalSetState?: (value: T) => void,
|
|
storageCondition?: (value: T, rawCurrentValue?: string | null) => boolean,
|
|
): [T, (value: T) => void] {
|
|
const [value, setValue] = useState(defaultValue);
|
|
|
|
useEffect(() => {
|
|
const item = localStorage.getItem(key);
|
|
|
|
if (!item && !storageCondition) {
|
|
localStorage.setItem(key, JSON.stringify(defaultValue));
|
|
} else if (!item && storageCondition && storageCondition(defaultValue)) {
|
|
localStorage.setItem(key, JSON.stringify(defaultValue));
|
|
}
|
|
|
|
const initialValue = item && item !== 'undefined' ? JSON.parse(item) : defaultValue;
|
|
setValue(initialValue);
|
|
if (globalSetState) {
|
|
globalSetState(initialValue);
|
|
}
|
|
|
|
function handler(e: StorageEvent) {
|
|
if (e.key !== key) {
|
|
return;
|
|
}
|
|
|
|
const lsi = localStorage.getItem(key);
|
|
setValue(JSON.parse(lsi ?? ''));
|
|
}
|
|
|
|
window.addEventListener('storage', handler);
|
|
|
|
return () => {
|
|
window.removeEventListener('storage', handler);
|
|
};
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [key, globalSetState]);
|
|
|
|
const setValueWrap = (value: T) => {
|
|
try {
|
|
setValue(value);
|
|
const storeLocal = () => {
|
|
localStorage.setItem(key, JSON.stringify(value));
|
|
window?.dispatchEvent(new StorageEvent('storage', { key }));
|
|
};
|
|
if (!storageCondition) {
|
|
storeLocal();
|
|
} else if (storageCondition(value, localStorage.getItem(key))) {
|
|
storeLocal();
|
|
}
|
|
globalSetState?.(value);
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
};
|
|
|
|
return [value, setValueWrap];
|
|
}
|