Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!