( 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: async (mutatedData) => { |
| 62 | const current = data; |
| 63 | // A read still in flight would land on top of this value and undo it. |
| 64 | await queryClient.cancelQueries({ queryKey }); |
| 65 | queryClient.setQueryData(queryKey, mutatedData); |
| 66 | return current; |
| 67 | }, |
| 68 | |
| 69 | onError: (_, __, rollback) => { |
| 70 | queryClient.setQueryData(queryKey, rollback); |
| 71 | }, |
| 72 | }); |
| 73 | |
| 74 | return [data ?? fallbackValue ?? null, updateValue, isFetched, isLoading]; |
| 75 | } |
| 76 | |
| 77 | export enum PersistentContextKeys { |
| 78 | BookmarkFoldersStripDismissedAt = 'bookmark_folders_strip_dismissed_at', |
no test coverage detected