Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React – Set state object using args

I have an object saved in a state I am trying to create a function to update parts of the object.

function removeError(val) {
    setPersonsState((prevState) => ({
      ...prevState,
      val: "",
    }));
  }

I have tried to pass val to the object key to update it.

onClick={removeError('Bob')}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Where Bob replaces val to update in the object. Sorry if terminology is bad.

>Solution :

Well, you should change it to be in the following way, sine you don’t want to change a key named val, but the key with name equal to the value of val

function removeError(val) {
    setPersonsState((prevState) => ({
        ...prevState,
        [val]: "",
    }));
}

And, as suggested in the comments by @RoshanKanwar, also the click handler is not correct, it should be

onClick = {() => removeError('Bob')}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading