fix: fix infinite query failure when conversationId is not found

This commit is contained in:
Daniel D Orlando 2023-04-10 14:55:39 -07:00
parent 478814ff1b
commit fb7542c865
2 changed files with 12 additions and 13 deletions

View file

@ -63,13 +63,11 @@ export const useGetConversationByIdQuery = (
//to make it work with how the Chat component is structured //to make it work with how the Chat component is structured
export const useGetConversationByIdMutation = ( export const useGetConversationByIdMutation = (
id: string, id: string,
callback: (data: t.TConversation) => void
): UseMutationResult<t.TConversation> => { ): UseMutationResult<t.TConversation> => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation(() => dataService.getConversationById(id), return useMutation(() => dataService.getConversationById(id),
{ {
onSuccess: (res: t.TConversation) => { onSuccess: (res: t.TConversation) => {
callback(res);
queryClient.invalidateQueries([QueryKeys.conversation, id]); queryClient.invalidateQueries([QueryKeys.conversation, id]);
}, },
} }

View file

@ -20,7 +20,7 @@ export default function Chat() {
//disabled by default, we only enable it when messagesTree is null //disabled by default, we only enable it when messagesTree is null
const messagesQuery = useGetMessagesByConvoId(conversationId, { enabled: false }); const messagesQuery = useGetMessagesByConvoId(conversationId, { enabled: false });
const getConversationMutation = useGetConversationByIdMutation(conversationId, setConversation); const getConversationMutation = useGetConversationByIdMutation(conversationId);
// when conversation changed or conversationId (in url) changed // when conversation changed or conversationId (in url) changed
useEffect(() => { useEffect(() => {
@ -31,7 +31,17 @@ export default function Chat() {
newConversation(); newConversation();
} else if (conversationId) { } else if (conversationId) {
// fetch it from server // fetch it from server
getConversationMutation.mutate(); getConversationMutation.mutate(conversationId, {
onSuccess: (data) => {
setConversation(data);
},
onError: (error) => {
console.error('failed to fetch the conversation');
console.error(error);
navigate(`/chat/new`);
newConversation();
}
});
setMessages(null); setMessages(null);
} else { } else {
navigate(`/chat/new`); navigate(`/chat/new`);
@ -45,15 +55,6 @@ export default function Chat() {
} }
}, [conversation, conversationId]); }, [conversation, conversationId]);
useEffect(() => {
if(getConversationMutation.isError) {
console.error('failed to fetch the conversation');
console.error(getConversationMutation.error);
newConversation();
}
}, [getConversationMutation.isError, newConversation]);
useEffect(() => { useEffect(() => {
if (messagesTree === null && conversation?.conversationId) { if (messagesTree === null && conversation?.conversationId) {
messagesQuery.refetch(conversation?.conversationId); messagesQuery.refetch(conversation?.conversationId);