()
| 5 | import { useAuthContext } from '@/providers/AuthProvider'; |
| 6 | |
| 7 | export function useChatList() { |
| 8 | const [chatListUpdated, setChatListUpdated] = useState(false); |
| 9 | const { isAuthorized } = useAuthContext(); |
| 10 | const { |
| 11 | data: chatData, |
| 12 | loading, |
| 13 | error, |
| 14 | refetch, |
| 15 | } = useQuery<{ getUserChats: Chat[] }>(GET_USER_CHATS, { |
| 16 | // Serve the cache instantly, refresh behind it: the invalidation flag |
| 17 | // this used to key on died with the sidebar, so a cache-first list went |
| 18 | // stale the moment a project was created or renamed elsewhere. |
| 19 | fetchPolicy: 'cache-and-network', |
| 20 | skip: !isAuthorized, |
| 21 | }); |
| 22 | |
| 23 | const handleRefetch = useCallback(() => { |
| 24 | refetch(); |
| 25 | }, [refetch]); |
| 26 | |
| 27 | const handleChatListUpdate = useCallback((value: boolean) => { |
| 28 | setChatListUpdated(value); |
| 29 | }, []); |
| 30 | |
| 31 | const sortedChats = useMemo(() => { |
| 32 | const chats = chatData?.getUserChats || []; |
| 33 | return [...chats].sort( |
| 34 | (a: Chat, b: Chat) => |
| 35 | new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime() |
| 36 | ); |
| 37 | }, [chatData?.getUserChats]); |
| 38 | |
| 39 | return { |
| 40 | chats: sortedChats, |
| 41 | loading, |
| 42 | error, |
| 43 | chatListUpdated, |
| 44 | setChatListUpdated: handleChatListUpdate, |
| 45 | refetchChats: handleRefetch, |
| 46 | }; |
| 47 | } |
no test coverage detected