Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
react-hook-form watch has wrong value after rendering select element

I'm using react-hook-form with a watch to detect the a change in a <select> but after populating the select, the watch initially has the wrong value.

Here's some code to illustrate the problem:

import React, { useState, useEffect } from 'react';
import { useForm } from "react-hook-form";

function App() {
  const { register, watch } = useForm();
  const watchFoo = watch("foo");
  const [foos, setFoos] = useState([]);

  useEffect(() => {
    setFoos([{ id: 1, name: "one" }, { id: 2, name: "two" }]);
  }, []);

  return (
    <form>
      <select {...register('foo')}>
        {foos.map((foo, i) => (<option key={`option_${i}`} value={foo.id}>{foo.name}</option>))}
      </select>
      <p>foo is {watchFoo}</p>
    </form>
  );
}

export default App;

https://codesandbox.io/s/mystifying-kate-8n9xu

The useEffect simulates fetching the values from the server when the component is first loaded.

On first render, watchFoo has the value undefined as expected. After calling setFoos it renders again with the drop-down having the value "one" selected, but watchFoo has the value "". After changing the value in the drop-down, watchFoo is correct, but it's just the initial value that is wrong.

Is there any solution or workaround for this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The "one" value hasn't actually had a selection event happen: it's just the first <option> in the list, so the rendered <select> shows it. The select element itself never had the events fire to update the internal form state with the new select box state. This causes a decoupling of the internal form state and the form state as represented in the page, because the browser will display the first option in the event that none of the options has the selected property (RFC 1866).

You can add an additional useEffect to update the hookform state when foos change:

  const { register, watch, setValue } = useForm();

  useEffect(() => {
    if(watchFoo === "" && foos.length > 0) {
      setValue("foo", foos[0].id);
    }
  }, [watchFoo, setValue, foos])

Another simpler option would be to just add an invisible blank option as your first entry:

<option style={{display: "none"}}></option>

This would result in your select showing a blank value by default, but without leaving the blank option as a selection option in your dropdown. This results in the form correctly reflecting the state of your internal form state, but wouldn't preselect the first option from the server. Select the technique which best fits your use case.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda