@prexo/ai-chat-sdk
Version:
AI Chat Component with Persistent History
27 lines (26 loc) • 799 B
JavaScript
import { useState, useEffect } from "react";
function useLocalStorage(key, initialValue) {
const isClient = typeof window !== "undefined";
const [storedValue, setStoredValue] = useState(() => {
if (!isClient) return initialValue;
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn("Failed to get from localStorage", error);
return initialValue;
}
});
useEffect(() => {
if (!isClient) return;
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.warn("Failed to set in localStorage", error);
}
}, [key, storedValue, isClient]);
return [storedValue, setStoredValue];
}
export {
useLocalStorage
};