Richard C
Richard C

Reputation: 171

Typescript React Passing parameter to setState

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 "").

Upvotes: 0

Views: 276

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282160

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.

Upvotes: 1

Related Questions