( key: string, valueWhenCacheEmpty?: T, validValues?: T[], fallbackValue?: T, )
| 29 | ]; |
| 30 | |
| 31 | export default function usePersistentContext<T>( |
| 32 | key: string, |
| 33 | valueWhenCacheEmpty?: T, |
| 34 | validValues?: T[], |
| 35 | fallbackValue?: T, |
| 36 | ): UserPersistentContextType<T> { |
| 37 | const queryKey = [key, valueWhenCacheEmpty]; |
| 38 | const queryClient = useQueryClient(); |
| 39 | |
| 40 | const { data, isFetched } = useQuery({ |
| 41 | queryKey, |
| 42 | queryFn: () => |
| 43 | getAsyncCache<T>(key, valueWhenCacheEmpty || null, validValues) || null, |
| 44 | }); |
| 45 | |
| 46 | const { mutateAsync: updateValue, isPending: isLoading } = useMutation({ |
| 47 | mutationFn: (value: T) => setCache(key, value), |
| 48 | |
| 49 | onMutate: (mutatedData) => { |
| 50 | const current = data; |
| 51 | queryClient.setQueryData(queryKey, mutatedData); |
| 52 | return current; |
| 53 | }, |
| 54 | |
| 55 | onError: (_, __, rollback) => { |
| 56 | queryClient.setQueryData(queryKey, rollback); |
| 57 | }, |
| 58 | }); |
| 59 | |
| 60 | return [data ?? fallbackValue, updateValue, isFetched, isLoading]; |
| 61 | } |
| 62 | |
| 63 | export enum PersistentContextKeys { |
| 64 | AlertPushKey = 'alert_push_key', |
no test coverage detected