buster/web/src/context/Chats/ChatProvider/useChatSelectors.ts

32 lines
1.1 KiB
TypeScript
Raw Normal View History

2025-02-11 11:15:32 +08:00
import type { IBusterChat, IBusterChatMessage } from '../interfaces';
2025-02-11 07:43:38 +08:00
import { useMemoizedFn } from 'ahooks';
2025-02-18 07:25:31 +08:00
import { useQueryClient } from '@tanstack/react-query';
import { queryKeys } from '@/api/query_keys';
export const useChatSelectors = () => {
const queryClient = useQueryClient();
2025-02-09 13:41:08 +08:00
2025-02-12 03:32:12 +08:00
const getChatMemoized = useMemoizedFn((chatId: string): IBusterChat | undefined => {
2025-02-18 07:25:31 +08:00
const options = queryKeys['chatsGetChat'](chatId);
const queryKey = options.queryKey;
return queryClient.getQueryData<IBusterChat>(queryKey);
2025-02-11 07:43:38 +08:00
});
const getChatMessagesMemoized = useMemoizedFn((chatId: string) => {
2025-02-18 07:25:31 +08:00
const chatMessageIds = getChatMemoized(chatId)?.messages || [];
return chatMessageIds.map((messageId) => getChatMessageMemoized(messageId));
2025-02-11 07:43:38 +08:00
});
const getChatMessageMemoized = useMemoizedFn((messageId: string) => {
2025-02-18 07:25:31 +08:00
const options = queryKeys['chatsMessages'](messageId);
const queryKey = options.queryKey;
return queryClient.getQueryData<IBusterChatMessage>(queryKey);
2025-02-11 07:43:38 +08:00
});
return {
getChatMemoized,
getChatMessagesMemoized,
getChatMessageMemoized
};
2025-02-09 13:41:08 +08:00
};