useNotifications.ts 891 B

12345678910111213141516171819202122232425262728293031323334
  1. import { useEffect } from "react";
  2. import { toast } from "sonner";
  3. import i18n from "i18next";
  4. export const useNotifications = () => {
  5. useEffect(() => {
  6. const eventSource = new EventSource(
  7. "http://localhost:8080/api/notifications/stream",
  8. );
  9. eventSource.addEventListener("order-update", (event) => {
  10. try {
  11. const payload = JSON.parse(event.data);
  12. toast.info(i18n.t(`sse.titles.${payload.type}`, "Powiadomienie systemowe"), {
  13. description: i18n.t(`sse.messages.${payload.type}`, { data: payload.data }),
  14. duration: 5000,
  15. });
  16. } catch (error) {
  17. console.error("Błąd dekodowania JSON z SSE:", error);
  18. }
  19. });
  20. eventSource.onerror = (error) => {
  21. console.error("Błąd kanału SSE:", error);
  22. eventSource.close();
  23. };
  24. return () => {
  25. eventSource.close();
  26. };
  27. }, []);
  28. };