All files / src/features/Minibuilders/Conversations/hooks useGetThreadMessages.ts

6.25% Statements 1/16
0% Branches 0/6
0% Functions 0/4
6.66% Lines 1/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 53 54 55 56 57 58 59                        21x                                                                                            
import { useAppSelector } from "@redux/hooks";
import { selectConversationTopic } from "@redux/slices/conversations";
import { customInstance } from "@services/api";
import { useQuery, useQueryClient } from "react-query";
import { Message } from "../Modal/types";
import { isEmpty } from "lodash";
import {
  QKEY_LIST_ACQUIRER_MERCHANTS,
  QKEY_LIST_ENTERPRISE_STATS,
  QKEY_LIST_ENTERPRISES,
} from "@constants/queryKeys";
 
const useGetThreadMessages = ({ merchantID }: { merchantID: number }) => {
  const queryClient = useQueryClient();
  const { queryObject } = useAppSelector(selectConversationTopic);
  const pathThread = queryObject?.paths?.find((item) => item.isConversation);
 
  const id = pathThread?.pathID;
  const threadId = id && id !== "new" ? id : null;
 
  const { data, isLoading, refetch } = useQuery(
    ["get-thread-messages", threadId],
    async () => {
      const data = await customInstance({
        url: `/merchants/${merchantID}/threads/${threadId}/messages?sort=-createdAt`,
      });
 
      await customInstance({
        url: `/merchants/${merchantID}/messages/read`,
        method: "POST",
        data: {
          threadID: threadId,
        },
      });
 
      return data;
    },
    {
      enabled: !!threadId,
      onSuccess: () => {
        queryClient.invalidateQueries(QKEY_LIST_ACQUIRER_MERCHANTS);
        queryClient.invalidateQueries(QKEY_LIST_ENTERPRISES);
        queryClient.invalidateQueries(QKEY_LIST_ENTERPRISE_STATS);
      },
    },
  );
 
  const messages: Message[] | undefined = data?.data;
 
  return {
    messages,
    isMessageResponse: !isEmpty(messages) && !isLoading,
    isLoading,
    refetch,
  };
};
 
export default useGetThreadMessages;