Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda