Next.js Discord

Discord Forum

react hook form and server actions

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
Hi guys, i am trying to ensure my button shows a loading status but i think i am getting something wrong. i ned you help

"use client";

  <Form {...form}>
    <form onSubmit={form.handleSubmit(onSubmit)} className="mx-auto max-w-4xl">
      <h2 className="text-2xl font-bold pb-10 ">{props.title}</h2>

      <div className="flex flex-col gap-6">
       
       .... form controls
          )}
        />
      </div>

      {/* button */}
      <div className="w-full pt-8">
        <SubmitButton
          loading={form.formState.isSubmitting}
          text="Get Syllabus"
        />
      </div>
    </form>
  </Form>;


this is the button component

"use client";
import { ReloadIcon } from "@radix-ui/react-icons";

type Props = {
  className?: string;
  text?: string;
  loading?: boolean;
};

export function SubmitButton({
  className,
  text = "Submit",
  loading = false,
}: Props) {
  return (
    <button
      type="submit"
      className={`bg-primary-400 w-full rounded-md text-white focus:outline-none focus:ring-0 cursor-pointer px-4 py-4 flex justify-center items-center hover:bg-primary-500 transition-all ${className}`}
      disabled={loading}
    >
      {loading && <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />}
      <span>{loading ? "Please wait" : text}</span>
    </button>
  );
}

8 Replies

Plott Hound
hi there. I have a few notes:
1. You are using onSubmit instead of action to submit your form. doc link:
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#forms

2. For pending states like your button you'll want to use a react hook called useFormStatus. doc link: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#pending-states

3. if you want pending status on event handlers that aren't inside forms you can use another react hook called useTransition. docs link: https://react.dev/reference/react/useTransition
Giant pandaOP
yes i am aware of not using the action in my form submission, its because its a client side form and i didnt think using server actions will work with react hook form since its a client side library.

i will try the usetransition hook
Giant pandaOP
yes infact i did but my issue is with the button not changing when submitting or after submission
initially i used useFormstatus but it didnt work
then i figured it works only when i use server actions when submitting the form
Plott Hound
can i see the code for handleSubmit?
@Giant panda then i figured it works only when i use server actions when submitting the form
Plott Hound
I thought you were using a server action based on the title of the post?