0

I am a beginner and I am doing this...

<i className="fa fa-trash-alt" onClick={() => this.handleDelete("trippurpose")} />

My handle delete is written like this...

handleDelete(whichitem: string) {
    // this handles someone changing an input text field
    console.log(whichitem);

    if (whichitem === "trippurpose") {
      this.setState({
        trippurpose: "",
      });
    } else if (whichitem === "projecttask") {
      this.setState({
        projecttask: "",
      });
    }
  }

What's I'd prefer to do is...

  handleDelete(whichitem: string) {
    // this handles someone changing an input text field

      this.setState({
        [whichitem]: "",
      });
  
    }

But when I do that I get an error... Argument of type `{[x: string]: string; }' is not assignable to parameter of type 'TemplatePopoverState | ((prevState: Readonly, props... and much more...

From reading up it seems that doing the [whichitem].

      this.setState({
        [whichitem]: "",
      });

Is the correct way to go but I suspect it's something in the method parameters that is wrong - any hints? As I said I am a complete novice..The ultimate goal is to call a function that pass a string that reflects the value of the input text field I want to clear (set to "").

1
  • Please share whole example Commented Mar 21, 2021 at 14:44

1 Answer 1

1

While setting dynamic value to setState, you need to specify the key to be one among the state keys, you can write the above funcition like

handleDelete(whichitem: keyof TemplatePopoverState) {
    // this handles someone changing an input text field

      this.setState({
        [whichitem]: "",
      } as Pick<TemplatePopoverState, keyof TemplatePopoverState>);
  
    }

For more reference refer this github issue.

Sign up to request clarification or add additional context in comments.

1 Comment

I had to make a small addition...adding as unknown (which someone mentioned in that github link). That's well above my knowledge base so THANK YOU. ``` handleDelete(whichitem: keyof TemplatePopoverState) { // this handles someone changing an input text field console.log(whichitem); this.setState(({ [whichitem]: "", } as unknown) as Pick<TemplatePopoverState, keyof TemplatePopoverState>); } ```

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.