Next.js Discord

Discord Forum

Is this normal in nextjs/react forms?

Unanswered
Noronha posted this in #help-forum
Open in Discord
I created a 'autocomplete' feature inside my 'Combobox' component.
It's pretty simple, user types, we go fetch data on server side with server-actions.

This is the structure:

  const [clients, setClients] = useState<ComboBoxItemType[]>([])

  const [contractId, setContractId] = useState<string | undefined>(
    transaction?.contractId || undefined
  )

  const handleClientSearchChanged = async (value: string) => {
    if (value === '' || value.length < 2) {
      return
    }

    const response = await listClients(1, value)

    if (response.type === 'error') {
      toaster.send(response)
      return
    }

    setClients(
      response.data?.data.map(client => ({
        value: client.id,
        label: client.nomeFantasia
      })) || []
    )
  }
  
// in JSX
        <div className='flex flex-col gap-2 sm:w-[25%]'>
          <Label>Client</Label>
          <Combobox
            value={clientId}
            items={clients}
            onSelect={value => setClientId(value)}
            selectItemMsg='Pesquise pelo cliente'
            searchPlaceholder='Pesquisar cliente...'
            onSearchChange={handleClientSearchChanged}
          />
        </div>


And also, since I'm in a form, I need this to load the client when we're editing a record:

  useEffect(() => {
    if (transaction?.clientId) {
      handleClientSearchChanged(transaction.clientId)
    }
  }, [transaction?.clientId])


As you can see that's a lot of code. Now imagine a form with 3 fields with autocomplete. How would I go about refactoring this? Maybe extracting some components?

Sorry if this is a dumb question. I'm a newbie on react/components/hooks/nextjs and all of it.
Thank you

3 Replies

I extracted a ClientAutocomplete component, it reduced alot the code on the form.
... and all of the autocompletes I have
Still this looks 'too much'. Or is it normal?