user10509524
user10509524

Reputation:

How to fix the error `Cannot read property 'setState' of undefined`

update 1:

I updated the fiddle but still I am facing an error _this.state.concat is not a function, can you please help me https://codesandbox.io/s/40mmrl9059

When I click the favourites icon in the card, then the card should be shown in the favourites tab which is the outer. For that I am trying to pass the value from child to the parent, so I am using setState in handleClick method.

But right now I am getting an error

Cannot read property 'setState' of undefined

Can you tell me how to fix it?

(providing my code snippet and sandbox below. - cards code is in actual-card.js and tab code is in tab-demo.js)

https://codesandbox.io/s/40mmrl9059

state = {
  value: 0,
  top: false,
  left: false,
  bottom: false,
  right: false,
  favorites: []
};

// props
handleClick(prop) {
  console.log("actualCard--->");
  //console.log("event.currentTarget--->", currentTarget.relatedTarget);
  this.setState({ favorites: this.state.concat(prop) });
}



<IconButton
  // onClick={this.handleClickOpen}
  onClick={this.handleClick}
  aria-label="Add to favorites"
>

<Tabs
  value={value}
  onChange={this.handleChange}
  scrollable
  scrollButtons="on"
  indicatorColor="primary"
  textColor="primary"
>
<Tab label="Search" icon={<PhoneIcon />} />
<Tab
  favorites={favorites}
  label="Favorites"
  icon={<FavoriteIcon />}
 />

Upvotes: 0

Views: 196

Answers (1)

Evan
Evan

Reputation: 232

You need to bind this to your event handler

Try using an arrow function like handleClick = (prop) => {//code}

Upvotes: 1

Related Questions