0

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.

1
  • 1
    Whenever you want to pass a parameter to a onClick handler function, you need to return that function in the form of arrow function. Like this - onClick = { () => removeError('Bob') } Commented Apr 29, 2022 at 10:24

1 Answer 1

2

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')}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.