Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

ConfigureDB.tsx

71 lines2.2 KB

1import { createIsomorphicFn } from "@tanstack/react-start";
2import { AnimatePresence, motion } from "motion/react";
3import { useEffect, useState } from "react";
4import { client } from "@/db";
5import { cn } from "@/lib/utils";
6import { Badge } from "./ui/badge";
7import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
8​
9/** Minimum time to show the loading state to avoid flickering */
10const MIN_DB_LOADING_TIME = 1_000;
11​
12const checkConnection = createIsomorphicFn().client(
13 async (cb: (state: boolean) => void) => {
14 if (client.ready) {
15 cb(true);
16 } else {
17 await client.waitReady;
18 cb(true);
19 }
20 },
21);
22​
23export function ConfigureDB() {
24 const [isConnected, setIsConnected] = useState(false);
25​
26 useEffect(() => {
27 let timeoutId: NodeJS.Timeout;
28 timeoutId = setTimeout(
29 () => checkConnection(setIsConnected),
30 MIN_DB_LOADING_TIME,
31 );
32 return () => clearTimeout(timeoutId);
33 }, []);
34​
35 return (
36 <Tooltip>
37 <div>
38 <AnimatePresence mode="wait" initial={false}>
39 <TooltipTrigger>
40 <motion.div
41 key={isConnected ? "connected" : "connecting"}
42 initial={{ opacity: 0, y: 10 }}
43 animate={{ opacity: 1, y: 0 }}
44 exit={{ opacity: 0, y: 10 }}
45 >
46 <Badge className="gap-2 bg-muted" variant="outline">
47 <div
48 className={cn(
49 "grow-0 h-2 w-2 rounded-full border",
50 isConnected
51 ? "bg-green-300"
52 : "animate-pulse bg-yellow-400",
53 )}
54 />
55 <span className="hidden lg:inline">
56 {isConnected ? "Connected to the db" : "Connecting to db..."}
57 </span>
58 <span className="inline lg:hidden">
59 {isConnected ? "Connected" : "Connecting"}
60 </span>
61 </Badge>
62 </motion.div>
63 </TooltipTrigger>
64 </AnimatePresence>
65 </div>
66 <TooltipContent>
67 This demo app runs a PGlite (Postgres in WASM) db instance locally.
68 </TooltipContent>
69 </Tooltip>
70 );