1

I have a handle delete that makes a request to a service.

  handleDelete = async studentId => {
    try {
      await axios.delete(`/students/${studentId}`).then(() =>
        this.setState({
          students: this.state.students.filter(
            student => student._id !== studentId
          ),
        })
      )
    } catch (e) {
      console.log(`Error: ${e}`)
    }
  }

When I commit out the a axios.delete and just call this.setState it does filter like I want it to.

Why is it that I can't force a rerender of the state with the new data?

Edit: this is my function on the backend to delete.

exports.deleteStudent = async (req, res) => {
  try {
    await Student.findByIdAndRemove(req.params.studentId)
    res.status(204)
  } catch (e) {
    console.log(`Error: ${e}`)
  }
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
Joseph Chambers
  • 3,698
  • 4
  • 22
  • 37

1 Answers1

1

Since you are using async-await, you need to resolve the promise. Also make use of functional setState.

handleDelete = async studentId => {
    try {
        await axios.delete(`/students/${studentId}`)
        this.setState(prevState => ({
          students: prevState.students.filter(
            student => student._id !== studentId
          )
        }))
    } catch (e) {
      console.log(`Error: ${e}`)
    }
  }

Check this for more details on when to use functional setState

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400