Next.js Discord

Discord Forum

how to handle form subit

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
hello, im currently facing an issue. i am building a form and i've created multiple client components that are inputs to this form. i have a dropzone for a file(one of the client components) and i want to take the file and send it with the other input info the the backend using an api call. how do i do that?

19 Replies

American black bearOP
the main issue im facing is to take the file data from the main general form
Thrianta
Normally I would track state in the parent form and pass the getter and setter to the child.

// parent
export fuction Form() {
  const [file, setFile] = useState<File|null>(null)

  return (
    <Dropzone 
      file={file}
      setFile={setFile}
   />   
  )
}


Then the child could call setFile to update the state in the parent form.
This would force the parent to be a client component though, fyi if using app router.
@Thrianta This would force the parent to be a client component though, fyi if using app router.
American black bearOP
yeah thats what im trying to avoid
i need the parent to be server side
Thrianta
I wonder if the dropzone has a valid <input type="file" /> elemenent inside it. if it does, and your <form /> wraps it correctly, the file might show up when the form is submitted (im guessing server action) in the formData. make sure the dropzone's <input /> has a type of file and a unique name like name="my-file", then in the server action that accepts formData: FormData as a parameter, check if formData.get("my-file") exists.
i would need to wrap my dropzone component in a form then right? wouldnt that create a nested form which is not allowed?
Thrianta
No I wouldn't nest the form. the parent form should be able to use its children <input/> elements. Can you check this by giving the dropzone a name attribute and checking the parent form's formData.get("my-file-input")?
im not good in coding im sorry if i ask stupid questions
Thrianta
no problem
show me how youre handling the parent form
American black bearOP
ive just noticed that ive built the form with react hook form which is client side based
but i didnt do much tbh
i can do the whole parent form again it wont slow me down much with progress
American black bearOP
the thing is, i have this select component that gets the options from a database and its the only server component really. if i find a way to get this component to work with the other client components my issue is solved really. @Thrianta
American black bearOP
do you have any ideas on how to do so? @Thrianta
Thrianta
Could you not fetch the options in another server component higher in the tree and then pass them down?