Home > Software design >  React - Set state object using args
React - Set state object using args

Time:04-30

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')}

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

CodePudding user response:

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')}
  • Related