Next.js Discord

Discord Forum

Async/Await when to use it?

Unanswered
Red-tailed wasp posted this in #help-forum
Open in Discord
Avatar
Red-tailed waspOP
Hello, any pros can explain when to use async/await? I'm currnetly anyhow spamming the async/await. Have no concept when or not to use it. :angy:

"use server";

import { getClient } from "@faustwp/experimental-app-router";
import { redirect } from "next/navigation";
import { SEND_PASSWORD_RESET_EMAIL } from "../../../gql/reset-password";
import { z } from "zod";
import { emailRegex } from "../../../utils/isValidEmail";

export async function resetPasswordAction(prevState: any, formData: FormData) {
  const usernameEmail = await formData.get("usernameEmail") as String;

  // Define schema for Zod
  const ResetPasswordDetails = await z.object({
    usernameEmail: z
      .string()
      .min(1, { message: "Email is required!" })
      .regex(emailRegex, { message: "Email is invalid!" }) 
      .transform((value) => value.toLowerCase()),
  });

  try {
    // Run validation with Zod
    const validated = ResetPasswordDetails.parse({ usernameEmail });

    const client = await getClient();

    const { data, errors } = await client.mutate({
      mutation: SEND_PASSWORD_RESET_EMAIL,
      variables: { username: validated.usernameEmail },
      errorPolicy: "all",
    });
//...

4 Replies

  const usernameEmail = await formData.get("usernameEmail") as String;

  // Define schema for Zod
  const ResetPasswordDetails = await z.object({
    usernameEmail: z
      .string()
      .min(1, { message: "Email is required!" })
      .regex(emailRegex, { message: "Email is invalid!" }) 
      .transform((value) => value.toLowerCase()),
  });
In these code blocks, you don't need await
Avatar
@Red-tailed wasp anything else?