Next.js Discord

Discord Forum

Form with Server Action but also Event Handlers?

Unanswered
American Sable posted this in #help-forum
Open in Discord
Avatar
American SableOP
Hey,

If I have a form component, something like that calls an external API via a server action

Form.tsx
export default function KycForm() {
  async function doSomething(formData: FormData) {
    "use server";
    const query = await fetch('domain.com');
    const response = await query.json();
    console.log(response);
    return response;
  }

  return (
    <Form action={doSomething} className="grid w-full items-start gap-6">
      <ComponentSettings doSomething={}/>
      <ResourceSettings />

      <button type="submit">Submit</button>
    </Form>
  );
}


How do I go about handling logic where, a change made to a form element in ComponentSettings would be able to trigger something in ResourceSettings? For example, a tickbox in one component, might trigger a dropdown in another?

If I use EventHandlers like above, Next errors because I cant use client side event handlers in a server component, but i can't make the form client side because i use a server action?

10 Replies

Avatar
Asian black bear
Yes you can make the form a client component.
Just pass the server action into it by importing it from another file.
Avatar
American SableOP
Bleugh, this new way of working causes so must nesting, importing and modularisation
Avatar
Asian black bear
Controlled forms really can't be fully server components by the nature of them.
Avatar
American SableOP
So lets say I now have my Form, it calls my action. How would I go about getting the response of that action back to the client, because I want the form and the response from that form to be on the same page
Avatar
Asian black bear
By using useActionState most likely.
Avatar
American SableOP
ok, but my KycForm is in nested in a page, and its another element on the page i need to pass the state to
so now my entire page route just became a client component, defeating the whole purpose of the SSR first flow
Avatar
American SableOP
so this being my page. My Form Components can do different things to other components. Ie, dropdown in A might change what shows in B

I then submit the form (pink) which the state is then passed to the other components
Image
Avatar
Asian black bear
If the content of a page is mostly interactive then so be it. This can happen sometimes.