使用Convex

使用 Convex 为你的应用添加数据库。


Convex 是一个基于 TypeScript 的数据库,不需要集群管理、SQL 或 ORM。Convex 提供通过 WebSocket 的实时更新,非常适合响应式应用。

1

安装 Convex

🌐 Install Convex

在你创建了你的 Expo 项目 后,使用以下命令安装 convex

🌐 After you have created your Expo project, install convex using the following command:

Terminal
npx expo install convex

2

设置 Convex 开发部署

🌐 Set up a Convex dev deployment

运行以下命令来设置你的 Convex 项目:

🌐 Run the following command to set up your Convex project:

Terminal
npx convex dev

这个命令:

🌐 This command:

  • 创建一个 Convex 账户或允许你登录。
  • 在 Convex 上创建一个项目。
  • 保存你的生产和部署网址。

它还会创建一个 convex/ 文件夹,你可以在其中编写 Convex 将托管的后端 API 函数。

🌐 It also creates a convex/ folder where you can write backend API functions that Convex will host.

在一个终端窗口中保持此命令运行,以便它能够将你的函数与 Convex 云中的开发部署同步。

🌐 Leave this command running in one terminal window so that it can sync your functions with your dev deployment in Convex's cloud.

3

将 Convex URL 保存为 EAS 环境变量

🌐 Save the Convex URL as an EAS environment variable

运行 npx convex dev 会将你的部署 URL 保存到 .env.local 文件中,命名为 EXPO_PUBLIC_CONVEX_URL。要在应用构建中使用它,请在新的终端会话中将其作为 EAS 环境变量 添加:

🌐 Running npx convex dev saves your deployment URL to a .env.local file as EXPO_PUBLIC_CONVEX_URL. To make it available in your app builds, add it as an EAS environment variable in a new terminal session:

Terminal
eas env:create --name EXPO_PUBLIC_CONVEX_URL --value https://YOUR_DEPLOYMENT_URL.convex.cloud --visibility plaintext --environment production --environment preview --environment development

https://YOUR_DEPLOYMENT_URL.convex.cloud 替换为你 .env.local 文件中的 EXPO_PUBLIC_CONVEX_URL 值。要了解更多信息,请参阅 环境变量

🌐 Replace https://YOUR_DEPLOYMENT_URL.convex.cloud with the EXPO_PUBLIC_CONVEX_URL value from your .env.local file. To learn more, see Environment variables.

4

初始化你的数据库

🌐 Seed your database

接下来,创建一个包含以下示例数据的 sampleData.jsonl 文件:

🌐 Next, create a sampleData.jsonl file with the following sample data:

sampleData.jsonl
{"text": "Buy groceries", "isCompleted": true} {"text": "Go for a swim", "isCompleted": true} {"text": "Integrate Convex", "isCompleted": false}

要将此数据发送到 Convex,请运行:

🌐 To send this data to Convex, run:

Terminal
npx convex import --table tasks sampleData.jsonl

5

查询数据库

🌐 Query the database

Convex 中的所有查询都是 TypeScript 代码。创建一个 convex/tasks.ts 文件,并包含以下内容:

🌐 All queries in Convex are TypeScript code. Create a convex/tasks.ts file with the following contents:

convex/tasks.ts
import { query } from './_generated/server'; export const get = query({ args: {}, handler: async ctx => { return await ctx.db.query('tasks').collect(); }, });

6

连接你的应用

🌐 Connect your app

在应用的顶层 src/app/_layout.tsx 文件中,创建一个 ConvexReactClient 并将其传递给封装组件树的 ConvexProvider

🌐 In the top-level src/app/_layout.tsx file in your app, create a ConvexReactClient and pass it to a ConvexProvider wrapping your component tree:

src/app/_layout.tsx
import { ConvexProvider, ConvexReactClient } from 'convex/react'; import { Stack } from 'expo-router'; const convex = new ConvexReactClient(process.env.EXPO_PUBLIC_CONVEX_URL!, { unsavedChangesWarning: false, }); export default function RootLayout() { return ( <ConvexProvider client={convex}> <Stack> <Stack.Screen name="index" /> </Stack> </ConvexProvider> ); }

7

在你的应用中显示数据

🌐 Display the data in your app

在你的应用中,使用 useQuery 钩子从你的 api.tasks.get API 获取数据:

🌐 In your app, use the useQuery hook to fetch data from your api.tasks.get API:

src/app/index.tsx
import { api } from '@/convex/_generated/api'; import { useQuery } from 'convex/react'; import { Text, View } from 'react-native'; export default function Index() { const tasks = useQuery(api.tasks.get); return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', }}> {tasks?.map(({ _id, text }) => ( <Text key={_id}>{text}</Text> ))} </View> ); }

下一步

🌐 Next steps

学习如何使用 Convex

在构建聊天应用的过程中了解 Convex 的工作原理。