import { createContext, useContext, useMemo, useEffect, ReactNode } from 'react';
type WSProviderProps = { children: ReactNode; url: string };
const WSStateContext = createContext<WebSocket | null>(null);
function WSProvider({ children, url }: WSProviderProps): JSX.Element {
const wsInstance = useMemo(
() => (typeof window != 'undefined' ? new WebSocket(`ws${window.location.protocol === 'https:' ? 's' : ''}://${window.location.host}${url}`) : null),
[]
);
// useEffect(() => {
// return () => {
// wsInstance?.close();
// };
// }, []);
return <WSStateContext.Provider value={wsInstance}>{children}</WSStateContext.Provider>;
}
function useWS(): WebSocket {
const context = useContext(WSStateContext);
if (!context) {
throw new Error('useWS must be used within a WSProvider');
}
return context;
}
// elsewhere, in a page:
import { NextPage } from "next";
import Head from "next/head";
import { FC, useEffect } from "react";
import { WSProvider, useWS } from "../utils/ws";
const ChatView: FC = () => {
let ws: WebSocket;
if (typeof window !== 'undefined') ws = useWS();
useEffect(() => {
ws.onopen = (e: Event) => console.log(e);
})
return (
<>
{/* shit */}
</>
);
};
const ChatPage: NextPage = () => {
return (
<WSProvider url="/api/socket">
<Head>
<title>Iridium Chat</title>
</Head>
<main className="h-screen w-screen bg-gray-50 dark:bg-slate-900">
<ChatView />
</main>
</WSProvider>
);
}
export default ChatPage;
import { createContext, useContext, useMemo, useEffect, ReactNode } from 'react';
type WSProviderProps = { children: ReactNode; url: string };
const WSStateContext = createContext<WebSocket | null>(null);
function WSProvider({ children, url }: WSProviderProps): JSX.Element {
const wsInstance = useMemo(
() => (typeof window != 'undefined' ? new WebSocket(`ws${window.location.protocol === 'https:' ? 's' : ''}://${window.location.host}${url}`) : null),
[]
);
// useEffect(() => {
// return () => {
// wsInstance?.close();
// };
// }, []);
return <WSStateContext.Provider value={wsInstance}>{children}</WSStateContext.Provider>;
}
function useWS(): WebSocket {
const context = useContext(WSStateContext);
if (!context) {
throw new Error('useWS must be used within a WSProvider');
}
return context;
}
// elsewhere, in a page:
import { NextPage } from "next";
import Head from "next/head";
import { FC, useEffect } from "react";
import { WSProvider, useWS } from "../utils/ws";
const ChatView: FC = () => {
let ws: WebSocket;
if (typeof window !== 'undefined') ws = useWS();
useEffect(() => {
ws.onopen = (e: Event) => console.log(e);
})
return (
<>
{/* shit */}
</>
);
};
const ChatPage: NextPage = () => {
return (
<WSProvider url="/api/socket">
<Head>
<title>Iridium Chat</title>
</Head>
<main className="h-screen w-screen bg-gray-50 dark:bg-slate-900">
<ChatView />
</main>
</WSProvider>
);
}
export default ChatPage;