Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  82] [ 2]  / answers: 1 / hits: 12795  / 2 Years ago, sat, march 26, 2022, 12:00:00

I am getting this error:



Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'setState')



and this is my code:


class Table extends Component {
constructor (props) {
super(props);
this.state = {
employees: [],
}
}
componentDidMount() {
this.getEmployeeList();
}
getEmployeeList = () => {
axios.get("employee/list")
.then(function(response) {

this.setState({
employees: response.data,
});

});
console.log(this.state.employees)
}

// Remaining codes

}

More From » reactjs

 Answers
37

This is because the callback you pass in is a function expression, which has its own this binding.


To solve this error you can:



  1. Use arrow functions:


getEmployeeList = () => {
axios
.get("employee/list")
.then((response) => {
this.setState({
employees: response.data,
});
});
};


  1. Save this to self variable, and call it instead:


getEmployeeList = () => {
const self = this;
axios
.get("employee/list")
.then(function (response) {
self.setState({
employees: response.data,
});
});
};

[#251] Tuesday, March 15, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
haylie

Total Points: 26
Total Questions: 108
Total Answers: 104

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
haylie questions
;