Wednesday, 30 November 2016

reactjs - Unable to run a function inside another function: Cannot read property 'test' of undefined / Cannot read property 'setState' of undefined



I want to run a callback test() from the onClose() function. I tried to find the solution across StackOverflow but I was unable to solve the problem. Running this code gives me undefined errors mentioned in the comments with codeblocks



constructor(props){

super(props)
this.state = {
isPaid: false
}
this.test = this.test.bind(this)
}
test = () =>{
const { isPaid } = this.state
console.log(isPaid)
this.setState({isPaid: true})

}

render() {
const isPaid = this.state
const {test} = this.props
let config = {
"publicKey": "*****",
"productIdentity": "1234567890",
"eventHandler": {
onSuccess (payload) {

console.log(payload);
},
onError (error) {
// handle errors
console.log(error);
},
onClose (){
console.log('widget is closing');
//Want to add some callback here to test()


const {test} = this.props //The issue is here
console.log(test) //getting Undefined
test(); //TypeError: Cannot read property 'test' of undefined


//OR

console.log(isPaid) //I get state as log
this.setState({isPaid: !isPaid}) //TypeError: Cannot read property 'setState' of undefined


}
}
};
let checkout = new paygateway(config);
return (




)


Answer



You're deconstructing test from this.props and the function doesn't exist in props. It's simply a function you've declared within the component. So, you should just assign test variable to the test function like so:



const test = this.test

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...