-
Notifications
You must be signed in to change notification settings - Fork 294
Expand file tree
/
Copy pathuseViewPost.ts
More file actions
43 lines (38 loc) · 1.4 KB
/
useViewPost.ts
File metadata and controls
43 lines (38 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import type { UseMutateAsyncFunction } from '@tanstack/react-query';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { sendViewPost } from '../../graphql/posts';
import { generateQueryKey, RequestKey } from '../../lib/query';
import { useAuthContext } from '../../contexts/AuthContext';
import type { UserStreak } from '../../graphql/users';
import { isSameDayInTimezone } from '../../lib/timezones';
export const useViewPost = (): UseMutateAsyncFunction<
unknown,
unknown,
string
> => {
const client = useQueryClient();
const { user } = useAuthContext();
const streakKey = generateQueryKey(RequestKey.UserStreak, user);
const readKey = generateQueryKey(RequestKey.ReadingStreak30Days, user);
const { mutateAsync: onSendViewPost } = useMutation({
mutationFn: sendViewPost,
onSuccess: async () => {
const streak = client.getQueryData<UserStreak>(streakKey);
const isNewStreak = !streak?.lastViewAt;
const isFirstViewToday =
!isNewStreak &&
!isSameDayInTimezone(
new Date(streak!.lastViewAt!),
new Date(),
user!.timezone,
);
if (isNewStreak || isFirstViewToday) {
await client.refetchQueries({ queryKey: streakKey });
// just mark the query as stale
await client.invalidateQueries({ queryKey: readKey });
}
return null;
},
});
return onSendViewPost;
};