This commit is contained in:
parent
4cc5893757
commit
684ac4660e
@ -1,32 +1,26 @@
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import {
|
import { ScoreSaberWebsocketMessageToken } from "@ssr/common/types/token/scoresaber/websocket/scoresaber-websocket-message";
|
||||||
ScoreSaberWebsocketMessageToken,
|
|
||||||
} from "@ssr/common/types/token/scoresaber/websocket/scoresaber-websocket-message";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connects to the ScoreSaber websocket.
|
* Connects to the ScoreSaber websocket.
|
||||||
* Waits until the page is loaded before establishing the connection.
|
|
||||||
*/
|
*/
|
||||||
export const useScoreSaberWebsocket = () => {
|
export const useScoreSaberWebsocket = () => {
|
||||||
const [connected, setConnected] = useState(false);
|
const [connected, setConnected] = useState(false);
|
||||||
const [message, setMessage] = useState<ScoreSaberWebsocketMessageToken | null>(null); // Store the incoming message
|
const [message, setMessage] = useState<ScoreSaberWebsocketMessageToken | null>(null); // Store the incoming message
|
||||||
const socketRef = useRef<WebSocket | null>(null);
|
const socketRef = useRef<WebSocket | null>(null);
|
||||||
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
const [isClient, setIsClient] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Only set isClient to true when we're on the client side
|
setMounted(true);
|
||||||
setIsClient(true);
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// If not on the client side, don't attempt to connect
|
if (!mounted) {
|
||||||
if (!isClient) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const connectWebSocket = () => {
|
const connectWebSocket = () => {
|
||||||
// Create a new WebSocket instance
|
|
||||||
socketRef.current = new WebSocket("wss://scoresaber.com/ws");
|
socketRef.current = new WebSocket("wss://scoresaber.com/ws");
|
||||||
|
|
||||||
socketRef.current.onopen = () => {
|
socketRef.current.onopen = () => {
|
||||||
@ -78,7 +72,7 @@ export const useScoreSaberWebsocket = () => {
|
|||||||
clearTimeout(reconnectTimeoutRef.current);
|
clearTimeout(reconnectTimeoutRef.current);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}, [isClient]); // Depend on isClient to ensure the code only runs on the client
|
}, [mounted]);
|
||||||
|
|
||||||
return { connected, message }; // Return both the connection status and the last received message
|
return { connected, message };
|
||||||
};
|
};
|
||||||
|
Reference in New Issue
Block a user