Next.js Discord

Discord Forum

How to elegantly handle form input components that need data from the server

Unanswered
Papillon posted this in #help-forum
Open in Discord
PapillonOP
Let's say I have a Form in Nextjs. Almost always, Forms tend to be client components due to the need for interactivity. Let's say the form relies on a custom form input component:

const UserSelect = async () => {
  const options = await db.select("name").from("users")
  return <select name="user">
    {options.map((opt) => <option value={name}>{name}</option>}
  </select>
}


As you can see, this form input relies on a DB fetch to populate its options, and is a server component. This means it can't be imported directly into a client component like a form. The alternative would be to have UserSelect accept props that populate the options:

"use client";
const UserSelect = ({users}) => {
  return <select name="user">
    {users.map((opt) => <option value={name}>{name}</option>}
  </select>
}


But this creates a bit of an odd DevX; now I need to do the fetch in some parent server component, and then drill down the results to wherever this select component is. The data fetch and the UI are no longer co-located, and if my UserSelect component is deeply nested in the React DOM, I'll need to do lots of prop drilling.

Is there an elegant solution to this situation using just Nextjs? Or do I need to use something like react query to allow data accesses to be colocated with UI for such components?

0 Replies