59 lines
1.6 KiB
TypeScript
59 lines
1.6 KiB
TypeScript
![]() |
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||
|
import React, { useState } from 'react';
|
||
|
|
||
|
export const useGlobalState = <T>(key: any[], initialData: T) => {
|
||
|
const queryClient = useQueryClient();
|
||
|
const stateQueries = useQuery<T>({
|
||
|
queryKey: key,
|
||
|
queryFn: () => Promise.reject('This thing never happens.'),
|
||
|
initialData,
|
||
|
staleTime: Infinity,
|
||
|
cacheTime: Infinity,
|
||
|
});
|
||
|
|
||
|
const setData = React.useCallback(
|
||
|
(param: React.SetStateAction<T>) => {
|
||
|
const oldState = queryClient.getQueryData<T>(key) as T;
|
||
|
queryClient.setQueryData(
|
||
|
key,
|
||
|
typeof param === 'function' ? (param as Function)(oldState) : param,
|
||
|
);
|
||
|
},
|
||
|
[queryClient, key],
|
||
|
);
|
||
|
|
||
|
return {
|
||
|
setData,
|
||
|
data: stateQueries.data,
|
||
|
};
|
||
|
};
|
||
|
|
||
|
export function useLocalStorage<T>(key: string, initialValue: T) {
|
||
|
const [storedValue, setStoredValue] = useState<T>(() => {
|
||
|
if (typeof window === 'undefined') {
|
||
|
return initialValue;
|
||
|
}
|
||
|
try {
|
||
|
const item = window.localStorage.getItem(key);
|
||
|
return item ? JSON.parse(item) : initialValue;
|
||
|
} catch (error) {
|
||
|
console.log(error);
|
||
|
return initialValue;
|
||
|
}
|
||
|
});
|
||
|
|
||
|
const setValue = (value: T | ((val: T) => T)) => {
|
||
|
try {
|
||
|
const valueToStore =
|
||
|
value instanceof Function ? value(storedValue) : value;
|
||
|
setStoredValue(valueToStore);
|
||
|
if (typeof window !== 'undefined') {
|
||
|
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
||
|
}
|
||
|
} catch (error) {
|
||
|
console.log(error);
|
||
|
}
|
||
|
};
|
||
|
return [storedValue, setValue] as const;
|
||
|
}
|