mirror of
https://github.com/Buriburizaem0n/nezha-dash-v1.git
synced 2026-02-04 12:40:10 +00:00
perf: use websocket context
This commit is contained in:
11
src/context/websocket-context.ts
Normal file
11
src/context/websocket-context.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { createContext } from "react";
|
||||
|
||||
export interface WebSocketContextType {
|
||||
sendMessage: (message: string) => void;
|
||||
lastMessage: MessageEvent | null;
|
||||
readyState: number;
|
||||
}
|
||||
|
||||
export const WebSocketContext = createContext<WebSocketContextType | undefined>(
|
||||
undefined,
|
||||
);
|
||||
34
src/context/websocket-provider.tsx
Normal file
34
src/context/websocket-provider.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import React from "react";
|
||||
import {
|
||||
WebSocketContext,
|
||||
type WebSocketContextType,
|
||||
} from "./websocket-context";
|
||||
import useWebSocket from "react-use-websocket";
|
||||
|
||||
interface WebSocketProviderProps {
|
||||
url: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const WebSocketProvider: React.FC<WebSocketProviderProps> = ({
|
||||
url,
|
||||
children,
|
||||
}) => {
|
||||
const { sendMessage, lastMessage, readyState } = useWebSocket(url, {
|
||||
reconnectAttempts: 10,
|
||||
reconnectInterval: 3000,
|
||||
shouldReconnect: () => true,
|
||||
});
|
||||
|
||||
const contextValue: WebSocketContextType = {
|
||||
sendMessage,
|
||||
lastMessage,
|
||||
readyState,
|
||||
};
|
||||
|
||||
return (
|
||||
<WebSocketContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</WebSocketContext.Provider>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user