MCPcopy Create free account
hub / github.com/dailydotdev/apps / useViewPost

Function useViewPost

packages/shared/src/hooks/post/useViewPost.ts:48–189  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

46}
47
48export 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 };

Callers 7

DigestPostContentRawFunction · 0.90
BriefPostContentRawFunction · 0.90
PollPostContentRawFunction · 0.90
useTrackPostViewFunction · 0.90
usePollVoteFunction · 0.90
renderViewPostFunction · 0.90

Calls 15

useRequestProtocolFunction · 0.90
useAuthContextFunction · 0.90
useStreakGoalCelebrationFunction · 0.90
generateQueryKeyFunction · 0.90
isSameDayInTimezoneFunction · 0.90
emitPatchyEventFunction · 0.90
isFinalViewRejectionFunction · 0.90
enqueueStreakViewFunction · 0.90
requestMethodFunction · 0.85
canBumpStreakFunction · 0.85

Tested by 1

renderViewPostFunction · 0.72