README.md

Welcome to your Convex functions directory!

Write your Convex functions here. See https://docs.convex.dev/functions for more.

A query function that takes two arguments looks like:

ts
1// functions.js
2import { query } from "./_generated/server";
3import { v } from "convex/values";
4
5export const myQueryFunction = query({
6 // Validators for arguments.
7 args: {
8 first: v.number(),
9 second: v.string(),
10 },
11
12 // Function implementation.
13 handler: async (ctx, args) => {
14 // Read the database as many times as you need here.
15 // See https://docs.convex.dev/database/reading-data.
16 const documents = await ctx.db.query("tablename").collect();
17
18 // Arguments passed from the client are properties of the args object.
19 console.log(args.first, args.second);
20
21 // Write arbitrary JavaScript here: filter, aggregate, build derived data,
22 // remove non-public properties, or create new objects.
23 return documents;
24 },
25});

Using this query function in a React component looks like:

ts
1const data = useQuery(api.functions.myQueryFunction, {
2 first: 10,
3 second: "hello",
4});

A mutation function looks like:

ts
1// functions.js
2import { mutation } from "./_generated/server";
3import { v } from "convex/values";
4
5export const myMutationFunction = mutation({
6 // Validators for arguments.
7 args: {
8 first: v.string(),
9 second: v.string(),
10 },
11
12 // Function implementation.
13 handler: async (ctx, args) => {
14 // Insert or modify documents in the database here.
15 // Mutations can also read from the database like queries.
16 // See https://docs.convex.dev/database/writing-data.
17 const message = { body: args.first, author: args.second };
18 const id = await ctx.db.insert("messages", message);
19
20 // Optionally, return a value from your mutation.
21 return await ctx.db.get(id);
22 },
23});

Using this mutation function in a React component looks like:

ts
1const mutation = useMutation(api.functions.myMutationFunction);
2function handleButtonPress() {
3 // fire and forget, the most common way to use mutations
4 mutation({ first: "Hello!", second: "me" });
5 // OR
6 // use the result once the mutation has completed
7 mutation({ first: "Hello!", second: "me" }).then((result) =>
8 console.log(result),
9 );
10}

Use the Convex CLI to push your functions to a deployment. See everything the Convex CLI can do by running npx convex -h in your project root directory. To learn more, launch the docs with npx convex docs.