-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuseChatList.ts
42 lines (36 loc) · 1.07 KB
/
useChatList.ts
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
import { useQuery } from '@apollo/client';
import { GET_USER_CHATS } from '@/graphql/request';
import { Chat } from '@/graphql/type';
import { useState, useCallback, useMemo } from 'react';
export function useChatList() {
const [chatListUpdated, setChatListUpdated] = useState(false);
const {
data: chatData,
loading,
error,
refetch,
} = useQuery<{ getUserChats: Chat[] }>(GET_USER_CHATS, {
fetchPolicy: chatListUpdated ? 'network-only' : 'cache-first',
});
const handleRefetch = useCallback(() => {
refetch();
}, [refetch]);
const handleChatListUpdate = useCallback((value: boolean) => {
setChatListUpdated(value);
}, []);
const sortedChats = useMemo(() => {
const chats = chatData?.getUserChats || [];
return [...chats].sort(
(a: Chat, b: Chat) =>
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
);
}, [chatData?.getUserChats]);
return {
chats: sortedChats,
loading,
error,
chatListUpdated,
setChatListUpdated: handleChatListUpdate,
refetchChats: handleRefetch,
};
}