Build a Finance SaaS Platform -6 (Database Connection)

Install react-query

1
npm i @tanstack/react-query

Add Provider

Add providers/query-provider.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// In Next.js, this file would be called: app/providers.jsx
"use client";

// Since QueryClientProvider relies on useContext under the hood, we have to put 'use client' on top
import {
isServer,
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'

function makeQueryClient() {
return new QueryClient({
defaultOptions: {
queries: {
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 60 * 1000,
},
},
})
}

let browserQueryClient: QueryClient | undefined = undefined

function getQueryClient() {
if (isServer) {
// Server: always make a new query client
return makeQueryClient()
} else {
// Browser: make a new query client if we don't already have one
// This is very important, so we don't re-make a new client if React
// suspends during the initial render. This may not be needed if we
// have a suspense boundary BELOW the creation of the query client
if (!browserQueryClient) browserQueryClient = makeQueryClient()
return browserQueryClient
}
}

type Props = {
children: React.ReactNode;
}

export function QueryProviders({ children }: Props) {
// NOTE: Avoid useState when initializing the query client if you don't
// have a suspense boundary between this and the code that may
// suspend because React will throw away the client on the initial
// render if it suspends and there is no boundary
const queryClient = getQueryClient()

return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}

Modify Layout.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import type { Metadata } from "next";
//import { Inter } from "next/font/google";
import "./globals.css";
import { ClerkProvider } from "@clerk/nextjs";
import { QueryProviders } from "@/providers/query-provider";

//const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
title: "Finance Demo",
description: "Finance Dashboard",
};

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<ClerkProvider>
<html lang="en">
<body>
<QueryProviders>
{children}
</QueryProviders>
</body>
</html>
</ClerkProvider>
);
}

Add Hook API

Add app/api/[[...route]]/route.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

import { Hono } from 'hono'
import { handle } from 'hono/vercel'

import accounts from "./accounts"

export const runtime = 'edge'

const app = new Hono().basePath('/api')

const routes = app.route("/accounts", accounts);

export const GET = handle(app);
export const POST = handle(app);

export type AppType = typeof routes;

Add app/api/[[...route]]/accounts.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

import { Hono } from "hono";
import { clerkMiddleware, getAuth } from "@hono/clerk-auth";
import { eq } from "drizzle-orm";

import {db} from "@/db/drizzle";
import {accounts} from "@/db/schema";

const app = new Hono()
.get("/", clerkMiddleware(), async (c) => {
const auth = getAuth(c);

if( !auth?.userId ) {
return c.json({ error:"Unauthorized!"}, 401);
}

const data = await db.select({
id: accounts.id,
name: accounts.name,
}).from(accounts)
.where(eq(accounts.userId, auth.userId));

return c.json({ accounts: data });
});

export default app;

Add Hook

Add features/accounts/api/use-get-accounts.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { useQuery } from "@tanstack/react-query";

import { client } from "@/lib/hono"

export const useGetAccounts = () => {
const query = useQuery({
queryKey: ["accounts"],
queryFn: async () => {
const res = await client.api.accounts.$get();

if(!res.ok){
throw new Error("Failed to fetch accounts");
}

const { accounts } = await res.json();
return accounts;
},
});

return query;
};

请我喝杯咖啡吧~

支付宝
微信