Home > Software engineering >  Change the value of all the fields in an object using useState hook
Change the value of all the fields in an object using useState hook

Time:06-15

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

CodePudding user response:

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 );

CodePudding user response:

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;
        }, {});
    });
}
  • Related