( key: string, valueWhenCacheEmpty?: T, validValues?: T[], fallbackValue?: T, )
| 41 | key: string, |
| 42 | ): UserPersistentContextType<T | null>; |
| 43 | export default function usePersistentContext<T>( |
| 44 | key: string, |
| 45 | valueWhenCacheEmpty?: T, |
| 46 | validValues?: T[], |
| 47 | fallbackValue?: T, |
| 48 | ): UserPersistentContextType<T | null> { |
| 49 | const queryKey = [key, valueWhenCacheEmpty]; |
| 50 | const queryClient = useQueryClient(); |
| 51 | |
| 52 | const { data, isFetched } = useQuery({ |
| 53 | queryKey, |
| 54 | queryFn: () => |
| 55 | getAsyncCache<T>(key, valueWhenCacheEmpty || null, validValues) || null, |
| 56 | }); |
| 57 | |
| 58 | const { mutateAsync: updateValue, isPending: isLoading } = useMutation({ |
| 59 | mutationFn: (value: T | null) => setCache(key, value), |
| 60 | |
| 61 | onMutate: (mutatedData) => { |
| 62 | const current = data; |
| 63 | queryClient.setQueryData(queryKey, mutatedData); |
| 64 | return current; |
| 65 | }, |
| 66 | |
| 67 | onError: (_, __, rollback) => { |
| 68 | queryClient.setQueryData(queryKey, rollback); |
| 69 | }, |
| 70 | }); |
| 71 | |
| 72 | return [data ?? fallbackValue ?? null, updateValue, isFetched, isLoading]; |
| 73 | } |
| 74 | |
| 75 | export enum PersistentContextKeys { |
| 76 | AlertPushKey = 'alert_push_key', |
no test coverage detected