#Is there a way to call mutations outside a component?
1 messages · Page 1 of 1 (latest)
Hi @sour marsh. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, there are several ways to call Convex mutations outside of React components:
1. Using ConvexHttpClient
You can use the ConvexHttpClient to call mutations from any JavaScript context:
const convex = new ConvexHttpClient(process.env.CONVEX_URL);
await convex.mutation(api.myFunctions.mutateSomething, { a: 1, b: 2 });
2. In Next.js Server Actions or Route Handlers
For Next.js applications, you can use the fetchMutation function:
import { fetchMutation } from "convex/nextjs";
import { api } from "@/convex/_generated/api";
// In a Server Action
async function createTask(formData: FormData) {
"use server";
await fetchMutation(api.tasks.create, {
text: formData.get("text") as string,
});
}
3. In TanStack Server Functions
For TanStack applications, you can use the ConvexHttpClient:
const convex = new ConvexHttpClient(import.meta.env.VITE_CONVEX_URL);
export const myServerFunction = createServerFn({
method: "POST",
})
.validator((input) => {
// Validation logic
return validatedInput;
})
.handler(async (ctx) => {
// Call mutation inside the handler
await convex.mutation(api.myFunctions.mutateSomething, { a: 1, b: 2 });
});
Important Notes
-
Don't call mutations directly as functions: Avoid calling mutation functions directly from other Convex functions. Instead, use
ctx.runMutationor extract shared logic into helper functions. -
For server-side authentication: When calling mutations from server contexts that require authentication, you'll need to pass the appropriate authentication token.
- Consider using helper functions: For code reuse across multiple Convex functions, it's recommended to extract shared logic into helper functions rather than calling mutations directly.