简体   繁体   中英

How to set array of object empty in state object using useState in React JS?

How to set array of object empty in state object using useState in React JS. I have below component on changing the drop down i need to set the object empty or remove from state object.

const FormComponent = () => {
  const [formValue, setFormValue] = useState({});
  
onChange = (value, field) => {
let value = {...formValue, value};
setFormValue(value);
}

  return (
 <>
// Form component goes here with input , dropdown. And having common onChange Method for all element
</>
)

}  

So, we have dropdown option like Admin, User Client. When Admin value selected from dropdown then below formValue object is coming

formValue = {
 admin: [{
text: "admin"
}],
content: "",
type: "Admin"
}

Now if i change the value from admin to "user" then form value showing as below

 formValue = {
     admin: [{
    text: "admin"
    }],
    user: [{
    text: "user"
    }],
    content: "",
    type: "User"
    }

How can i remove the admin object property/empty array object from the formValue Object whenever i change the dropwdown value from admin to user.

Only it should store respective property whenever drop down value have like Admin, User Client

Just change your onChange function to this

onChange = (value, field) => {
  setFormValue(value); 
}

The problem with the below statement that it is combining the formValue and the value

let value = {...formValue, value}; // **value** 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM