-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusePosts.ts
More file actions
52 lines (47 loc) · 1.35 KB
/
Copy pathusePosts.ts
File metadata and controls
52 lines (47 loc) · 1.35 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
44
45
46
47
48
49
50
51
52
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { UserProfile } from '../types/user';
import { postsApi } from '../api/postsApi';
import StaleTime from '../constants/staletime.ts';
export interface Post {
id: number;
content: string;
timestamp: Date;
expiresIn: number;
author: UserProfile;
imageUrl?: string;
}
export const usePosts = () => {
const qc = useQueryClient();
const {data: posts = [],isLoading,isError,refetch,} = useQuery<Post[]>({
queryKey: ['posts'],
queryFn: postsApi.fetchPosts,
staleTime: StaleTime.OneMinute,
});
const createPostMutation = useMutation({
mutationFn: postsApi.createPost,
onSuccess: newPost => {
qc.setQueryData<Post[]>(['posts'], prev =>
[newPost, ...(prev ?? [])].filter(p => {
const expireAt = p.timestamp.getTime() + p.expiresIn * 60 * 60 * 1000;
return Date.now() < expireAt;
})
);
},
});
return {
posts,
isLoading,
isError,
refetch,
createPost: createPostMutation.mutateAsync,
};
};
// Hook for fetching posts by username
export const usePostsByUsername = (username: string) => {
return useQuery<Post[]>({
queryKey: ['posts', 'user', username],
queryFn: () => postsApi.fetchPostsByUsername(username),
staleTime: StaleTime.TwoMinutes,
enabled: !!username,
});
};