All files / src/features/GiveNotificationModal/hooks useNotificationActions.ts

43.47% Statements 10/23
50% Branches 6/12
25% Functions 2/8
42.85% Lines 9/21

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 60 61 62 63 64 65 66                      116x 116x 116x 116x 116x 116x                                                                 116x 1x                         116x    
import {
  QKEY_ALL_NOTIFICATIONS,
  QKEY_CHECK_NEW_NOTIFICATIONS,
} from "@constants/queryKeys";
import { useAppSelector } from "@redux/hooks";
import { selectSelectedAccount } from "@redux/slices/auth/accounts";
import { selectUser } from "@redux/slices/auth/auth";
import { markAsRead } from "@services/api/notifications/user";
import { useMutation, useQueryClient } from "react-query";
 
export default function useNotificationActions() {
  const selectedUser = useAppSelector(selectSelectedAccount);
  const user = useAppSelector(selectUser);
  const merchantId = selectedUser?.id || 0;
  const userId = user?.userAccID || 0;
  const queryClient = useQueryClient();
  const markAsReadMutation = useMutation(
    (notificationsIds: (string | number)[]) => {
      return markAsRead(merchantId, userId, notificationsIds);
    },
    {
      onSuccess(_, notificationIds) {
        const queryKey = [QKEY_ALL_NOTIFICATIONS, userId, merchantId];
        queryClient.invalidateQueries([
          QKEY_CHECK_NEW_NOTIFICATIONS,
          merchantId,
          userId,
        ]);
        queryClient.setQueryData(queryKey, (oldData: any) => {
          if (!oldData) return oldData;
 
          const idSet = new Set(notificationIds);
 
          return {
            ...oldData,
            pages: oldData.pages.map((page: any) => ({
              ...page,
              data: page.data.map((notification: any) =>
                idSet.has(notification.id)
                  ? { ...notification, readAt: new Date().toISOString() }
                  : notification,
              ),
            })),
          };
        });
      },
    },
  );
 
  const markAllAsReadNotification = () => {
    Eif (!userId || !merchantId) return;
 
    markAsReadMutation.mutate(["*"], {
      onSuccess: () => {
        queryClient.invalidateQueries([QKEY_ALL_NOTIFICATIONS, userId]);
        queryClient.invalidateQueries([
          QKEY_CHECK_NEW_NOTIFICATIONS,
          merchantId,
          userId,
        ]);
      },
    });
  };
  return { markAsReadMutation, markAllAsReadNotification };
}