Rest API CRUD – Node.js + express + React.js + MySQL Part 7: Delete

Node.js (Backend)

Route

nodebackend/src/routes/EmployeeRoute.js

router.post('/delete',EmployeeController.delete);

Controller

nodebackend/src/controllers/EmployeeController.js

controllers.delete = async (req, res) => {
  // parameter post
  const { id } = req.body;
  // delete sequelize
  const del = await Employee.destroy({
    where: { id: id}
  })
  res.json({success:true,deleted:del,message:"Deleted successful"});
}

React.js ( Frontend )

appnode/src/module/list.js

<button class="btn btn-outline-danger" onClick={()=>this.onDelete(data.id)}> Delete </button>

Sweetalert

https://github.com/sweetalert2/sweetalert2

//instalar
npm install --save sweetalert2
// instalar sccs
npm install node-sass

Importar libreria

//sweetalert2
import Swal from 'sweetalert2/dist/sweetalert2.js'
import 'sweetalert2/src/sweetalert2.scss'

Funcion para confirmar de eliminar

 onDelete(id){
    Swal.fire({
      title: 'Are you sure?',
      text: 'You will not be able to recover this imaginary file!',
      type: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'No, keep it'
    }).then((result) => {
      if (result.value) {
        this.sendDelete(id)
      } else if (result.dismiss === Swal.DismissReason.cancel) {
        Swal.fire(
          'Cancelled',
          'Your imaginary file is safe :)',
          'error'
        )
      }
    })
  }

funcion para enviar y eliminar al backend

  sendDelete(userId)
  {
    // url de backend
    const baseUrl = "http://localhost:3000/employee/delete"    // parameter data post
    // network
    axios.post(baseUrl,{
      id:userId
    })
    .then(response =>{
      if (response.data.success) {
        Swal.fire(
          'Deleted!',
          'Your employee has been deleted.',
          'success'
        )
      }
    })
    .catch ( error => {
      alert("Error 325 ")
    })
  }

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *