Next.js Discord

Discord Forum

Form structure

Unanswered
Noronha posted this in #help-forum
Open in Discord
  const loadedDate = fuel?.date
    ? parse(fuel.date, 'dd-MM-yyyy', new Date())
    : undefined

  const [errors, setErrors] = useState<string[] | undefined>(undefined)
  const [driverId, setDriverId] = useState<string | undefined>(fuel?.driverId)
  const [value, setValue] = useState<number | string>(fuel?.value || '')
  const [date, setDate] = useState<Date | undefined>(loadedDate)

  const closeRef = useRef<ElementRef<'button'>>(null)

  const onSubmit = async (id: string | null) => {
    if (!date) {
      setErrors(['Data inválida.'])
      return
    }

    const dto = {
      date: format(date, 'dd-MM-yyyy'),
      truckId: truckId!,
      driverId: driverId!,
      value: Number(value)
    }

    const response = await saveOrUpdate(dto, id)

    if (response?.type === 'success') {
      toaster.send(response)
      closeRef.current?.click()
    }
  }

  const submitFn = fuel
    ? onSubmit.bind(null, fuel.id)
    : onSubmit.bind(null, null)

  return (
        <form action={submitFn}>
          <div className='flex flex-col gap-3'>
            <Label>Data</Label>
            <DatePicker className='w-full' date={date} onSelect={setDate} />

            <Label>Motorista</Label>
            <Combobox
              className='min-w-full'
              value={driverId}
              onSelect={setDriverId}
              items={driversItems}
              searchPlaceholder='Pesquisar motorista...'
              noResultsMsg='Nenhum motorista encontrado'
              selectItemMsg='Selecione um motorista'
            />

            // Truck input here

            <Label htmlFor='value'>Valor</Label>
            <MoneyInput
              className='w-full'
              name='value'
              placeholder='Valor do abastecimento'
              value={value}
              setValue={setValue}
            />
          </div>
// Other

6 Replies

Sorry for sending it on two messages but it was too long of a question. I have a complex form with a bunch of relationships and using third party libs. So I ended up with a form that looks way different from the docs, with FormData.

Is this wrong for any reason? I saw a "react beginners mistakes" video on youtube that said it was an error using state for forms, when you should really use 'ref' (something like that).

But I dont know. If there's errors, can you help me fix them? 🙂
Any one?
try this :
https://react-hook-form.com/

its flexible
check if you can find what u need exactly
and if its gonna fit ur needs ...
I saw that before, but that's my problem. My submit function doesnt even have an FormData, because of all the libs in using (MoneyInput/Combobox/DatePicker etc). I did see in the docs some kind of wrapper, called Controller