89 lines
2.9 KiB
JavaScript
89 lines
2.9 KiB
JavaScript
import { useEffect, useState, useRef } from "react";
|
|
import SocketIO from "socket.io-client";
|
|
import { auth } from "../../firebase/firebase.utils";
|
|
import { store } from "../../redux/store";
|
|
import { setWssStatus } from "../../redux/application/application.actions";
|
|
const useSocket = (bodyshop) => {
|
|
const socketRef = useRef(null);
|
|
const [clientId, setClientId] = useState(null);
|
|
|
|
useEffect(() => {
|
|
const unsubscribe = auth.onIdTokenChanged(async (user) => {
|
|
if (user) {
|
|
const newToken = await user.getIdToken();
|
|
|
|
if (socketRef.current) {
|
|
// Send new token to server
|
|
socketRef.current.emit("update-token", newToken);
|
|
} else if (bodyshop && bodyshop.id) {
|
|
// Initialize the socket
|
|
const endpoint = import.meta.env.PROD ? import.meta.env.VITE_APP_AXIOS_BASE_API_URL : "";
|
|
|
|
const socketInstance = SocketIO(endpoint, {
|
|
path: "/wss",
|
|
withCredentials: true,
|
|
auth: { token: newToken },
|
|
reconnectionAttempts: Infinity,
|
|
reconnectionDelay: 2000,
|
|
reconnectionDelayMax: 10000
|
|
});
|
|
|
|
socketRef.current = socketInstance;
|
|
|
|
const handleBodyshopMessage = (message) => {
|
|
if (!import.meta.env.DEV) return;
|
|
console.log(`Received message for bodyshop ${bodyshop.id}:`, message);
|
|
};
|
|
|
|
const handleConnect = () => {
|
|
console.log("Socket connected:", socketInstance.id);
|
|
socketInstance.emit("join-bodyshop-room", bodyshop.id);
|
|
setClientId(socketInstance.id);
|
|
store.dispatch(setWssStatus("connected"))
|
|
};
|
|
|
|
const handleReconnect = (attempt) => {
|
|
console.log(`Socket reconnected after ${attempt} attempts`);
|
|
store.dispatch(setWssStatus("connected"))
|
|
};
|
|
|
|
const handleConnectionError = (err) => {
|
|
console.error("Socket connection error:", err);
|
|
store.dispatch(setWssStatus("error"))
|
|
};
|
|
|
|
const handleDisconnect = () => {
|
|
console.log("Socket disconnected");
|
|
store.dispatch(setWssStatus("disconnected"))
|
|
};
|
|
|
|
socketInstance.on("connect", handleConnect);
|
|
socketInstance.on("reconnect", handleReconnect);
|
|
socketInstance.on("connect_error", handleConnectionError);
|
|
socketInstance.on("disconnect", handleDisconnect);
|
|
socketInstance.on("bodyshop-message", handleBodyshopMessage);
|
|
}
|
|
} else {
|
|
// User is not authenticated
|
|
if (socketRef.current) {
|
|
socketRef.current.disconnect();
|
|
socketRef.current = null;
|
|
}
|
|
}
|
|
});
|
|
|
|
// Clean up the listener on unmount
|
|
return () => {
|
|
unsubscribe();
|
|
if (socketRef.current) {
|
|
socketRef.current.disconnect();
|
|
socketRef.current = null;
|
|
}
|
|
};
|
|
}, [bodyshop]);
|
|
|
|
return { socket: socketRef.current, clientId };
|
|
};
|
|
|
|
export default useSocket;
|