3. データベース設定
Convexを利用する
Convex | The fullstack TypeScript development platform
The backend application platform with everything you need to build your product.

Convexの設定
ドキュメントに沿ってインストール
Next.js Quickstart | Convex Developer Hub
Add Convex to a Next.js project

terminal
$ bun add convex
installed convex@1.16.0 with binaries:
- convex
convexの起動。初回はログインが必要なので指示に従って進めていく(GitHubで認証)
terminal
$ bunx convex dev
Welcome to developing with Convex, let's get you logged in.
? Device name: kubozu
Visit https://auth.convex.dev/activate?user_code=XXXX-XXXX to finish logging in.
You should see the following code which expires in 15 minutes: XXXX-XXXX
? Open the browser? Yes
✔ Saved credentials to ~/.convex/config.json
? Do you agree to the Terms of Service at https://convex.dev/legal/v2022-03-02/tos Yes
認証が通ったらそのままプロジェクト作成
terminal
? Project name: slack-tutorial
✔ Provisioned a dev deployment and saved its:
name as CONVEX_DEPLOYMENT to .env.local
URL as NEXT_PUBLIC_CONVEX_URL to .env.local
convexディレクトリや .env.local
にURL追加される
convexは別途起動しないと接続できないので、Next.jsの起動と別個に起動させる。
terminal
$ bun dev
terminal
$ bunx convex dev
手順に従ってサンプルデータを格納
sampleData.jsonl
{"text": "Buy groceries", "isCompleted": true}
{"text": "Go for a swim", "isCompleted": true}
{"text": "Integrate Convex", "isCompleted": false}
terminal
bunx convex import --table tasks sampleData.jsonl
convexディレクトリにデータ取得タスクを作成
convex/tasks.ts
import { query } from "./_generated/server";
export const get = query({
args: {},
handler: async (ctx) => {
return await ctx.db.query("tasks").collect();
},
});
プロバイダを作成
src/components/convex-client-provider.tsx
"use client";
import { ConvexProvider, ConvexReactClient } from "convex/react";
import { ReactNode } from "react";
const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!);
export function ConvexClientProvider({ children }: { children: ReactNode }) {
return <ConvexProvider client={convex}>{children}</ConvexProvider>;
}
src/app/layout.tsx
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<ConvexClientProvider>{children}</ConvexClientProvider>
</body>
</html>
);
}
testページ
src/app/test/page.tsx
"use client";
import { useQuery } from "convex/react";
import { api } from "../../../convex/_generated/api";
const Page = () => {
const tasks = useQuery(api.tasks.get);
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
{tasks?.map(({ _id, text }) => <div key={_id}>{text}</div>)}
</main>
);
};
export default Page;
ここまででリアルタイムにデータベースからデータが取得できるようになる