import { useQuery, useQueryClient } from '@tanstack/react-query'; import React, { useState } from 'react'; export const useGlobalState = (key: any[], initialData: T) => { const queryClient = useQueryClient(); const stateQueries = useQuery({ queryKey: key, queryFn: () => Promise.reject('This thing never happens.'), initialData, staleTime: Infinity, cacheTime: Infinity, }); const setData = React.useCallback( (param: React.SetStateAction) => { const oldState = queryClient.getQueryData(key) as T; queryClient.setQueryData( key, typeof param === 'function' ? (param as Function)(oldState) : param, ); }, [queryClient, key], ); return { setData, data: stateQueries.data, }; }; export function useLocalStorage(key: string, initialValue: T) { const [storedValue, setStoredValue] = useState(() => { 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; }