0

I have a crud app to manage students, I want to refresh the student listing whenever I delete a student. But when I am calling the refresh function in the delete function it is throwing an error that my refresh function is not a function. Below is the code of both functions:

deleteStudent(studentId) {
        axios.delete('http://localhost:4000/students/delete-student/' + studentId)
        .then((res) => {
            console.log('Student successfully deleted!')
            this.loadStudents()
            
        })
        .catch((error) => {
            console.log(error)
        })
    }

loadStudents() {
        axios.get('http://localhost:4000/students/')
        .then(res => {
            this.setState({
                students: res.data
            });
        })
        .catch((error) => {
            console.log(error);
        })
    }

Prior thanks for any help!

Kevin
  • 1
  • 5
  • You haven't bind your function. Or you can use arrow function: loadStudents = () => {...}. – JB_DELR Dec 18 '20 at 08:34
  • Declare `loadStudents` *before* `deleteStudent`. Also, ensure proper `this` bindings always. – Drew Reese Dec 18 '20 at 08:34
  • The order of the functions doesn't matter, obviously. – JB_DELR Dec 18 '20 at 08:40
  • Can you add some code showing where `deleteStudent` is called. How a function is called determines what the value of `this` is. – Ed_ Dec 18 '20 at 08:40
  • you need to filter students in state by student id after removing student – isa_toltar Dec 18 '20 at 08:42
  • This is why you have to bind the function to (this) in the constructor to get this class as scope. But with arrow function this is this class anyway. – JB_DELR Dec 18 '20 at 08:43
  • @IsaToltar, yes if you don't want to reload all students, but you need the server awnser to know if the deletion worked before delete it in the local store to be sync with your data base. This is more efficient if the server return just a status or an HTTP_CODE when you send a DELETE (crud) methode (less data to transfert). – JB_DELR Dec 18 '20 at 08:54
  • @JB_DELR Binding the deleteStudent to (this) in the constructor solved the issue. Thanks a ton. Thank you, everybody. – Kevin Dec 18 '20 at 09:13
  • Please consider arrow function for less code, and @IsaToltar comment because it's not necessary to overload your server. – JB_DELR Dec 18 '20 at 09:17
  • @JB_DELR IsaToltar Sure I will take that into account, thanks for the suggestion. – Kevin Dec 18 '20 at 09:23

0 Answers0