Spaces:
Sleeping
Sleeping
File size: 1,280 Bytes
dbcdc7c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | import { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';
const OptionsContext = createContext();
const getStoredOptions = () => {
try {
return JSON.parse(localStorage.getItem('options') || '{}');
} catch {
return {};
}
};
export const OptionsProvider = ({ children }) => {
const [options, setOptions] = useState(getStoredOptions);
useEffect(() => {
try {
localStorage.setItem('options', JSON.stringify(options));
} catch {}
}, [options]);
const updateOption = useCallback((obj, immediate = true) => {
if (!obj || typeof obj !== 'object') return;
const current = getStoredOptions();
const updated = { ...current, ...obj };
try {
localStorage.setItem('options', JSON.stringify(updated));
} catch {}
if (immediate) {
setOptions((prev) => ({ ...prev, ...obj }));
}
}, []);
const contextValue = useMemo(() => ({ options, updateOption }), [options, updateOption]);
return <OptionsContext.Provider value={contextValue}>{children}</OptionsContext.Provider>;
};
export const useOptions = () => {
const context = useContext(OptionsContext);
if (!context) {
throw new Error('useOptions must be used within an OptionsProvider');
}
return context;
};
|