fix: enhance broadcast channel logic

This commit is contained in:
yassinedorbozgithub
2025-01-29 19:42:10 +01:00
parent 30c142f5b6
commit 961ca05d33
11 changed files with 211 additions and 284 deletions

View File

@@ -9,6 +9,7 @@
import { useEffect } from "react";
import { useMutation, useQuery, useQueryClient } from "react-query";
import { useBroadcastChannel } from "@/contexts/broadcast-channel.context";
import { EntityType, TMutationOptions } from "@/services/types";
import { ILoginAttributes } from "@/types/auth/login.types";
import {
@@ -22,7 +23,6 @@ import { useSocket } from "@/websocket/socket-hooks";
import { useFind } from "../crud/useFind";
import { useApiClient } from "../useApiClient";
import { CURRENT_USER_KEY, useAuth, useLogoutRedirection } from "../useAuth";
import { useBroadcastChannel } from "../useBroadcastChannel";
import { useTabUuid } from "../useTabUuid";
import { useToast } from "../useToast";
import { useTranslate } from "../useTranslate";
@@ -60,10 +60,8 @@ export const useLogout = (
const { logoutRedirection } = useLogoutRedirection();
const { toast } = useToast();
const { t } = useTranslate();
const { useBroadcast } = useBroadcastChannel();
const broadcastLogoutAcrossTabs = useBroadcast("session");
const tabUuidRef = useTabUuid();
const tabUuid = tabUuidRef.current;
const { postMessage } = useBroadcastChannel();
const uuid = useTabUuid();
return useMutation({
...options,
@@ -74,10 +72,7 @@ export const useLogout = (
},
onSuccess: async () => {
queryClient.removeQueries([CURRENT_USER_KEY]);
broadcastLogoutAcrossTabs({
value: "logout",
uuid: tabUuid || "",
});
postMessage({ data: "logout", tabId: uuid.current || "" });
await logoutRedirection();
toast.success(t("message.logout_success"));
},

View File

@@ -1,104 +0,0 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import * as React from "react";
import { useContext } from "react";
import {
BroadcastChannelContext,
BroadcastChannelData,
IBroadcastChannelContext,
} from "@/contexts/broadcast-channel.context";
export const useBroadcast = <
T extends BroadcastChannelData = BroadcastChannelData,
>(
channelName: string,
handleMessage?: (event: MessageEvent<T>) => void,
handleMessageError?: (event: MessageEvent<T>) => void,
): ((data: T) => void) => {
const channelRef = React.useRef<BroadcastChannel | null>(
typeof window !== "undefined" && "BroadcastChannel" in window
? new BroadcastChannel(channelName + "-channel")
: null,
);
useChannelEventListener(channelRef.current, "message", handleMessage);
useChannelEventListener(
channelRef.current,
"messageerror",
handleMessageError,
);
return (data: T) => channelRef.current?.postMessage(data);
};
export const useBroadcastState = <
T extends BroadcastChannelData = BroadcastChannelData,
>(
channelName: string,
initialState: T,
): [T, React.Dispatch<React.SetStateAction<T>>, boolean] => {
const [isPending, startTransition] = React.useTransition();
const [state, setState] = React.useState<T>(initialState);
const broadcast = useBroadcast<T>(channelName, (ev) => setState(ev.data));
const updateState: React.Dispatch<React.SetStateAction<T>> =
React.useCallback(
(input) => {
setState((prev) => {
const newState = typeof input === "function" ? input(prev) : input;
startTransition(() => broadcast(newState));
return newState;
});
},
[broadcast],
);
return [state, updateState, isPending];
};
const useChannelEventListener = <K extends keyof BroadcastChannelEventMap>(
channel: BroadcastChannel | null,
event: K,
handler?: (e: BroadcastChannelEventMap[K]) => void,
) => {
const callbackRef = React.useRef(handler);
if (callbackRef.current !== handler) {
callbackRef.current = handler;
}
React.useEffect(() => {
const callback = callbackRef.current;
if (!channel || !callback) {
return;
}
channel.addEventListener(event, callback);
return () => {
channel.close();
channel.removeEventListener(event, callback);
};
}, [channel, event]);
};
export const useBroadcastChannel = (): IBroadcastChannelContext => {
const context = useContext(BroadcastChannelContext);
if (!context) {
throw new Error(
"useBroadcastChannel must be used within an BroadcastChannelContext",
);
}
return context;
};

View File

@@ -11,18 +11,20 @@ import { useRef } from "react";
import { generateId } from "@/utils/generateId";
const getOrCreateTabId = () => {
let tabId = sessionStorage.getItem("tab_uuid");
let storedTabId = sessionStorage.getItem("tab_uuid");
if (!tabId) {
tabId = generateId();
sessionStorage.setItem("tab_uuid", tabId);
if (storedTabId) {
return storedTabId;
}
return tabId;
storedTabId = generateId();
sessionStorage.setItem("tab_uuid", storedTabId);
return storedTabId;
};
export const useTabUuid = () => {
const tabUuidRef = useRef<string | null>(getOrCreateTabId());
const tabUuidRef = useRef<string>(getOrCreateTabId());
return tabUuidRef;
};