Files
TX/artifacts/tx-os/src/hooks/use-notifications-socket.ts
T

74 lines
2.1 KiB
TypeScript
Raw Normal View History

import { useEffect } from "react";
import { io } from "socket.io-client";
import { useQueryClient } from "@tanstack/react-query";
import {
getListNotificationsQueryKey,
getGetHomeStatsQueryKey,
getListMyServiceOrdersQueryKey,
getListIncomingServiceOrdersQueryKey,
getListAppsQueryKey,
getGetMeQueryKey,
} from "@workspace/api-client-react";
import { useAuth } from "@/contexts/AuthContext";
const BASE = import.meta.env.BASE_URL.replace(/\/$/, "");
export function useNotificationsSocket() {
const { user } = useAuth();
const queryClient = useQueryClient();
useEffect(() => {
if (!user) return;
const socket = io(window.location.origin, {
path: `${BASE}/api/socket.io`,
});
socket.on("notification_created", (payload?: { type?: string }) => {
queryClient.invalidateQueries({ queryKey: getListNotificationsQueryKey() });
queryClient.invalidateQueries({ queryKey: getGetHomeStatsQueryKey() });
if (payload?.type === "order") {
queryClient.invalidateQueries({
queryKey: getListMyServiceOrdersQueryKey(),
});
queryClient.invalidateQueries({
queryKey: getListIncomingServiceOrdersQueryKey(),
});
}
});
socket.on("order_updated", () => {
queryClient.invalidateQueries({
queryKey: getListMyServiceOrdersQueryKey(),
});
queryClient.invalidateQueries({
queryKey: getListIncomingServiceOrdersQueryKey(),
});
});
2026-04-22 06:37:01 +00:00
socket.on("order_deleted", () => {
queryClient.invalidateQueries({
queryKey: getListMyServiceOrdersQueryKey(),
});
queryClient.invalidateQueries({
queryKey: getListIncomingServiceOrdersQueryKey(),
});
});
socket.on("order_incoming_changed", () => {
queryClient.invalidateQueries({
queryKey: getListIncomingServiceOrdersQueryKey(),
});
});
socket.on("apps_changed", () => {
queryClient.invalidateQueries({ queryKey: getListAppsQueryKey() });
queryClient.invalidateQueries({ queryKey: getGetMeQueryKey() });
});
return () => {
socket.disconnect();
};
}, [user, queryClient]);
}