| 46 | } |
| 47 | |
| 48 | export const useViewPost = (): UseMutateAsyncFunction< |
| 49 | unknown, |
| 50 | unknown, |
| 51 | string, |
| 52 | ViewPostContext |
| 53 | > => { |
| 54 | const client = useQueryClient(); |
| 55 | const { requestMethod, isCompanion } = useRequestProtocol(); |
| 56 | const { user } = useAuthContext(); |
| 57 | // the companion keeps waiting for the server value |
| 58 | const isOptimistic = !isCompanion; |
| 59 | const celebrateStreakDay = useStreakDailyCelebration(); |
| 60 | const checkStreakEarnBack = useStreakEarnBackProgress(); |
| 61 | const celebrateStreakGoal = useStreakGoalCelebration(); |
| 62 | const streakKey = generateQueryKey(RequestKey.UserStreak, user); |
| 63 | const readKey = generateQueryKey(RequestKey.ReadingStreak30Days, user); |
| 64 | const { mutateAsync: onSendViewPost } = useMutation< |
| 65 | unknown, |
| 66 | unknown, |
| 67 | string, |
| 68 | ViewPostContext |
| 69 | >({ |
| 70 | mutationFn: (id: string) => requestMethod(VIEW_POST_MUTATION, { id }), |
| 71 | onMutate: () => { |
| 72 | const streak = client.getQueryData<UserStreak>(streakKey); |
| 73 | const isNewStreak = !streak?.lastViewAt; |
| 74 | const isFirstViewToday = |
| 75 | !isNewStreak && |
| 76 | !isSameDayInTimezone( |
| 77 | new Date(streak!.lastViewAt!), |
| 78 | new Date(), |
| 79 | user!.timezone, |
| 80 | ); |
| 81 | const shouldRefetchStreak = isNewStreak || isFirstViewToday; |
| 82 | const nextStreak = |
| 83 | streak && canBumpStreak(streak, user?.timezone) |
| 84 | ? streak.current + 1 |
| 85 | : undefined; |
| 86 | |
| 87 | if (!isOptimistic || !shouldRefetchStreak || nextStreak === undefined) { |
| 88 | return { shouldRefetchStreak, nextStreak }; |
| 89 | } |
| 90 | |
| 91 | const optimisticStreak: UserStreak = { |
| 92 | ...streak!, |
| 93 | current: nextStreak, |
| 94 | total: streak!.total + 1, |
| 95 | max: Math.max(streak!.max, nextStreak), |
| 96 | lastViewAt: new Date(), |
| 97 | }; |
| 98 | client.setQueryData<UserStreak>(streakKey, optimisticStreak); |
| 99 | |
| 100 | return { |
| 101 | previousStreak: streak, |
| 102 | optimisticStreak, |
| 103 | shouldRefetchStreak, |
| 104 | nextStreak, |
| 105 | }; |