#Is there a way to call mutations outside a component?

1 messages · Page 1 of 1 (latest)

sour marsh
#

Is there a way to call mutations outside a component?

sand ledgeBOT
#

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,
  });
}

Next.js Server Rendering

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

  1. Don't call mutations directly as functions: Avoid calling mutation functions directly from other Convex functions. Instead, use ctx.runMutation or extract shared logic into helper functions.

  2. For server-side authentication: When calling mutations from server contexts that require authentication, you'll need to pass the appropriate authentication token.

#
  1. 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.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: