All files / react-app/src/api useGetSystemNotifs.ts

72% Statements 18/25
63.63% Branches 7/11
66.66% Functions 6/9
73.91% Lines 17/23

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            72x 12x     72x 37x 37x   37x 12x 12x 12x     37x 11x     37x 37x 15x     37x               37x       37x                
import { API } from "aws-amplify";
import { useState, useEffect } from "react";
import { useGetUser } from "@/api";
import { useQuery } from "@tanstack/react-query";
import { BannerNotification, ReactQueryApiError } from "shared-types";
 
export const getSystemNotifs = async (): Promise<BannerNotification[]> => {
  return await API.get("os", "/systemNotifs", {});
};
 
export const useGetSystemNotifs = () => {
  const userQuery = useGetUser();
  const [dismissed, setDismissed] = useState<string[]>([]);
 
  useEffect(() => {
    const dismissedNotifs = localStorage.getItem(`notifs.${userQuery?.data?.user?.username}`);
    const parsed: string[] = JSON.parse(dismissedNotifs) ?? [];
    setDismissed(parsed);
  }, [userQuery?.data?.user?.username]);
 
  const result = useQuery<BannerNotification[], ReactQueryApiError>(["systemBannerNotifs"], () =>
    getSystemNotifs(),
  );
 
  const notDismissed = result.data?.filter((i) => !dismissed.includes(i.notifId)) ?? []; //check dismissed
  const currentNotifs = notDismissed.filter(
    (i) => i.expDate && new Date(i.expDate).getTime() > new Date().getTime(),
  ); //check expired
 
  const clearNotif = (id?: string) => {
    const toBeRemoved = id ?? currentNotifs?.[0]?.notifId ?? "";
    const cleared = [...dismissed, toBeRemoved].filter((v, i, a) => a.indexOf(v) === i);
 
    setDismissed(cleared);
    localStorage.setItem(`notifs.${userQuery?.data?.user?.username}`, JSON.stringify(cleared));
  };
 
  const resetNotifs = () => {
    setDismissed([]);
    localStorage.setItem(`notifs.${userQuery?.data?.user?.username}`, JSON.stringify([]));
  };
  return {
    notifications: currentNotifs,
    dismissed: dismissed,
    allNotifications: result.data ?? [],
    clearNotif: clearNotif,
    resetNotifs: resetNotifs,
  };
};