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

99
Visualizações
Add element to array setState React

I have useState "setAnswers" (set) and "answers" (get) (answers is array with strings)
and click trigger:

onClick = () => {
    setAnswers((prev) => [...prev, e]) 
    setValue(questionKey, answers)
    console.log(watch(questionKey))
}

but with ever click i got only previous value

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

0

In fact, your console.log is execute before the state finish to be calculated, if you put your console.log on an other place, normally, you find what you want.

Try it, and say me

about 4 years ago · Juan Pablo Isaza Relatório

0

Your console.log(watch(questionKey)) all time will go wrong on onChange.

you need use a useEffect to log or make anything else with state as base.

    useEffect(() => {
     console.log(watch(questionKey)
    }, [questionKey]);

to more info you can read here: https://dev.to/mpodlasin/react-useeffect-hook-explained-in-depth-on-a-simple-example-19ec

about 4 years ago · Juan Pablo Isaza Relatório

0

I think you are a little bit confused: watch function from useForm is used to

Watch specified inputs and return their values.

So console.log(watch(questionKey)) does make no sense.

watch should be used in this way:

  React.useEffect(() => {
    const subscription = watch((value, { name, type }) => console.log(value, name, type));
    return () => subscription.unsubscribe();
  }, [watch]);

You use a useEffect to subscribe/unsubscribe watch on some form fields, and then in component's body you could call:

const watchSomething = watch(<something>);

and, every time the field called <something> will change his value, watch will execute console.log(value, name, type).

If you want to print the very last value of a state variable, you should know that setValue, setAnswer are async functions and its absolutely not guaranteed that on next line you could log the last value. To solve your problem you have 2 choices:

  1. use watch correctly;

  2. forget watch and use classic useEffect:

    onClick = () => {
       setAnswers((prev) => [...prev, e]) 
       setValue(questionKey, answers)
    }
    
    useEffect(() => {
       console.log(questionKey); //<-- here you will print the very last value of questionKey
    }, [questionKey]);
    

Here a guide on how to use watch.

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