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

135
Visualizações
Change the value of all the fields in an object using useState hook

import { useState } from "react";

function useForm(initialfields) {
  const [value, setValue] = useState(initialfields);
  const reset = () =>
    Object.keys(value).forEach((param) => setValue({ ...value, [param]: "" }));

  //setValue(Object.keys(value).forEach((val) => (value[val] = "")));
  return [value, handleChange, reset];
}

export default useForm;

I am trying to reset the value of all the fields in the object using setState. However, the following code only resets the value in the last field. Let's say Value = {username:"Sam123",name:"Sam"}, then my current code is returning {username:"Sam123",name:""} instead of {username:"",name:""} [1]: https://i.stack.imgur.com/urdmM.png

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

You are updating a state value using its previous value. You need to use the callback argument of the state setter. https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Also instead of calling the state setter (setValue) for each key, iterate inside the state setter callback. This causes the state setter to be called only once.

function reset() {
    setValue((value)=>{ // use previous value of value
        return Object.keys(value).reduce((acc,key)=>{
            acc[key] = ''; // set each key to empty string
            return acc;
        }, {});
    });
}
about 4 years ago · Santiago Gelvez Relatório

0

I think you might just be overcomplicating it just a little bit.

Instead of using the setValue function and expanding the array to feed into it, the forEach method is already doing the iteration over each key/value pair. It's like you're trying to do double work.

Instead of this: Object.keys(value).forEach((param) => setValue({ ...value, [param]: "" }));

See below:

let obj = {"username":"Sam123","name":"Sam"};

console.log( obj );

Object.keys(obj).forEach(key => obj[key] = "" );

console.log( obj );

about 4 years ago · Santiago Gelvez 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