Using Convex
Edit page
Add a database to your app with Convex.
Convex is a TypeScript-based database that requires no cluster management, SQL, or ORMs. Convex provides real-time updates over a WebSocket, making it perfect for reactive apps.
1
Install Convex
After you have created your Expo project, install convex using the following command:
- npx expo install convex2
Set up a Convex dev deployment
Run the following command to set up your Convex project:
- npx convex devThis command:
- Creates a Convex account or allows you to log in.
- Creates a project on Convex.
- Saves your production and deployment URLs.
It also creates a convex/ folder where you can write backend API functions that Convex will host.
Leave this command running in one terminal window so that it can sync your functions with your dev deployment in Convex's cloud.
3
Save the Convex URL as an EAS environment variable
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:
- eas env:create --name EXPO_PUBLIC_CONVEX_URL --value https://YOUR_DEPLOYMENT_URL.convex.cloud --visibility plaintext --environment production --environment preview --environment developmentReplace 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
Next, create a sampleData.jsonl file with the following sample data:
{"text": "Buy groceries", "isCompleted": true} {"text": "Go for a swim", "isCompleted": true} {"text": "Integrate Convex", "isCompleted": false}
To send this data to Convex, run:
- npx convex import --table tasks sampleData.jsonl5
6
Connect your app
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:
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
In your app, use the useQuery hook to fetch data from your api.tasks.get API:
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
Learn how Convex works while building a chat app.