Coolguy
Coolguy

Reputation: 2285

Error of 'this' when trying to setState in Modal

I'm trying to do a delete confirmation modal.

  handleDelete (){
console.log('handleDelete')
const { something} = this.state
confirm({
  title: 'Are you sure you want delete?',
  content: 'Press Ok to continue, Cancel to return',
  onOk () {
    console.log('onOK')
    this.setState({ something: [] })
  }
})

}

After I press the delete button, the confirmation modal will show. If user press ok, then it will delete something behind the confirmation modal.

But the delete can't be done. I have the error message:

TypeError: this is undefined

on this line:

this.setState({ something: [] })

Is it that I trying to setstate on an unmounted component? Then what is the correct way?

Upvotes: 0

Views: 1061

Answers (3)

Linh Đinh Văn
Linh Đinh Văn

Reputation: 11

you can use Arrow function, it worked.

onOk: () => { console.log('onOK') this.setState({ something: [] }) }

Upvotes: 1

msolvaag
msolvaag

Reputation: 66

class Something extends React.Component {
constructor(props) {
    super(props);

    this.handleDelete = this.handleDelete.bind(this);
}

handleDelete() {
    console.log('handleDelete');
    const { something } = this.state;

    confirm({
        title: 'Are you sure you want delete?',
        content: 'Press Ok to continue, Cancel to return',
        onOk: () => {
            console.log('onOK')
            this.setState({ something: [] })
        },
        onOkWithoutArrow: function(){
           this.setState({..});
        }.bind(this);
    });
}

render() {
    return <Component onClick={this.handleDelete} />;
}
}

Upvotes: 0

Sagiv b.g
Sagiv b.g

Reputation: 31024

You haven't posted the code for your component but if you are using a class component then any method that declared inside a class should hard bind the this object to the class instance so you could get access to the state object that "lives" inside this instance.

This is usually done in the constructor of the class:

constructor(props){
  super(props);
  this.handleDelete = this.handleDelete.bind(this);
}

Another approach is to use the ES6 arrow functions which will use the lexical context for the this key word, that means, if your handler is declared inside a class then the lexical context of this method is the class itself, hence the this key word will reference to the class.

handleDelete = () => {
  // your code...
}

Upvotes: 0

Related Questions