Skip to content

Commit 7fa1e4e

Browse files
committed
Connection status
1 parent f06f94a commit 7fa1e4e

File tree

3 files changed

+47
-4
lines changed

3 files changed

+47
-4
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import type { TRPCConnectionState } from "@trpc/client/unstable-internals";
2+
import { useEffect, useState } from "react";
3+
import { wsClient } from "utils/trpc";
4+
5+
const useConntectionStatus = () => {
6+
const [connectionState, setConnectionState] =
7+
useState<TRPCConnectionState<unknown> | null>(null);
8+
9+
useEffect(() => {
10+
const { unsubscribe } = wsClient.connectionState.subscribe({
11+
next: (state) => {
12+
setConnectionState(state);
13+
},
14+
});
15+
16+
return () => unsubscribe();
17+
}, []);
18+
19+
return connectionState;
20+
};
21+
22+
export const ConnectionStatus = () => {
23+
const connectionState = useConntectionStatus();
24+
25+
console.log("Connection State:", connectionState?.state);
26+
27+
if (!connectionState) return <div className="badge">Loading...</div>;
28+
29+
if (connectionState.state === "connecting") {
30+
return <div className="badge badge-accent">Connecting</div>;
31+
}
32+
33+
if (connectionState.state === "idle") {
34+
return <div className="badge badge-success">Idle</div>;
35+
}
36+
37+
return <div className="badge badge-success">Connected</div>;
38+
};

apps/client/src/routes/__root.tsx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
Outlet,
77
} from "@tanstack/react-router";
88
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
9+
import { ConnectionStatus } from "components/ConnectionStatus";
910

1011
export const Route = createRootRouteWithContext<{
1112
queryClient: QueryClient;
@@ -25,6 +26,9 @@ function RootComponent() {
2526
return (
2627
<>
2728
<div className="w-screen h-screen relative overflow-x-hidden">
29+
<div className="absolute top-2 mx-auto left-0 right-0 w-fit z-50">
30+
<ConnectionStatus />
31+
</div>
2832
<div className={"absolute min-h-full"}>
2933
<Outlet />
3034
</div>

apps/client/src/utils/trpc.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,15 @@ const secure = location.protocol === "https:";
77

88
export const queryClient = new QueryClient();
99

10+
export const wsClient = createWSClient({
11+
url: `${secure ? "wss" : "ws"}://${location.host}/trpc`,
12+
})
13+
1014
const trpcClient = createTRPCClient<AppRouter>({
1115
links: [wsLink({
12-
client: createWSClient({
13-
url: `${secure ? "wss" : "ws"}://${location.host}/trpc`,
14-
}),
16+
client: wsClient,
1517
}),],
1618
});
17-
1819
export const trpc = createTRPCOptionsProxy<AppRouter>({
1920
client: trpcClient,
2021
queryClient,

0 commit comments

Comments
 (0)