Next.js Discord

Discord Forum

How to handle loading state in nextjs14?

Unanswered
Champagne D’Argent posted this in #help-forum
Open in Discord
Champagne D’ArgentOP
Hi I have this component and currently I am trying to get my head around the problem to show a loading state once the user tries to login.
I thought of adding a state and just updating it on signIn, but that would require the component to be a client component.

This is the component:

export default function Login({
  searchParams,
}: {
  searchParams: { message: string };
}) {
  const signIn = async (formData: FormData) => {
    "use server";

    const email = formData.get("email") as string;
    const password = formData.get("password") as string;
    const cookieStore = cookies();
    const supabase = createClient(cookieStore);

    const { error } = await supabase.auth.signInWithPassword({
      email,
      password,
    });

    if (error) {
      return redirect("/login?message=Could not authenticate user");
    }

    return redirect("/");
  };

  return (
    <div className="flex-1 flex flex-col w-full px-8 sm:max-w-md justify-center gap-2">
      <form
        className="animate-in flex-1 flex flex-col w-full justify-center gap-2 text-foreground"
        action={signIn}
      >
        <Label className="text-md" htmlFor="email">
          Email
        </Label>
        <Input
          className="rounded-md px-4 py-2 bg-inherit border mb-6"
          name="email"
          placeholder="you@example.com"
          required
        />
        <Label className="text-md" htmlFor="password">
          Password
        </Label>
        <Input
          className="rounded-md px-4 py-2 bg-inherit border mb-6"
          type="password"
          name="password"
          placeholder="..."
          required
        />
        <Button>Sign In</Button>
        <SignUpButton />
        {searchParams?.message && (
          <p className="mt-4 p-4 bg-foreground/10 text-foreground text-center">
            {searchParams.message}
          </p>
        )}
      </form>
    </div>
  );
}

1 Reply

Wuchang bream
You would need to keep that as a server component and create a client component within there. Possibly pass a function as a prop to the login button and handle clicking login through there. Then you can use a state to show Sign In or a loading icon based on that.