Reputation:
I am working on a simple crud app that has data coming in and getting filled in a react-table and it has simple crud operations of add and delete.
But I am getting this error: TypeError: Cannot read property 'setState' of undefined
import SweetAlert from "react-bootstrap-sweetalert";
then wrote a method: (it's outside the class)
const successAlert = () => {
console.log("alertttttttttttttttttttttttt");
this.setState({
alert: (
<SweetAlert
alert={this.state.alert}
success
title="Good job!"
onConfirm={this.onConfirm}
onCancel={this.onCancel}
>
You clicked the button!
</SweetAlert>
),
});
};
and this is my the class:
constructor(props) {
super(props);
this.state = {
alert: null,
data: dataTable.map((prop, key) => {
return {
id: key,
name: prop[0],
position: prop[1],
office: prop[2],
age: prop[3],
actions: (
<div className="actions-right">
<Button
fill="true"
onClick={() => {
var data = this.state.data;
data.find((o, i) => {
if (o.id === key) {
data.splice(i, 1);
console.log(data);
console.log(i);
return true;
}
return false;
});
successAlert();
this.setState({
data: data,
});
}}
color="danger"
size="sm"
className="btn-icon btn-link remove"
id="tooltip974171201"
>
<i className="fa fa-times" />
</Button>
<UncontrolledTooltip
delay={0}
target="tooltip974171201"
placement="top"
>
Delete this record
</UncontrolledTooltip>
</div>
),
};
}),
};
}
Upvotes: 0
Views: 477
Reputation: 1893
You've mentioned that (it's outside the class)
.
this keyword has scope only within the class hence it's giving you the error. Move that method inside the class.
Ex:
this.state = {
showAlert: false
}
showAlert() {
this.setState({ showAlert: true });
}
render() {
return(
<SweetAlert
alert={this.state.showAlert}>
You clicked the button!
</SweetAlert>
<button onClick={this.showAlert.bind(this)}>Show Alert</button>
)
}
Upvotes: 1