NodeJS + Express + React Hooks + MySQL – #8 Delete

NodeJS + Express

Controller

src/controllers/CustomerController.js

const controller = {}
// import model
var Customers = require('../models/Customers');

 
 controller.delete = async (req, res) => {

  try {

    // parameter get id
    const { id } = req.params;
    // delete sequelize
    const response = await Customers.destroy({
      where: { id: id }
    })
    .then(function(data){
      const res = { success: true, deleted: data, message: "Customer succesfully deleted" }
      return res;
    })
    .catch(error=>{
      const res = { success: false, message: error.message }
      return res;
    })

    res.json(response);

  } catch (e) {

    const response = { success: false, message: e.message }
    res.json(response)

  }

}

module.exports = controller;

Routes

src/routes/api.js

const express = require('express');
const router = express.Router();
//import controller
const customerController = require('./../controllers/CustomerController');

router.delete('/customer/delete/:id', customerController.delete);

module.exports = router;

React

SweetAlert

npm install sweetalert --save

List

src/views/js/components/customer/List.js

import React, { useEffect, useState  } from 'react';

import customerService from "../../services/Customer"

import { Link } from 'react-router-dom';
import swal from 'sweetalert';

function List(){

  const [ listCustomer, setListCustomer ] = useState([]);
  const [ isLoading, setLoading ] = useState(false);
  const [ messageDeleted, setMessageDelete ] = useState(null)

  useEffect(()=>{

    async function fetchDataCustomer(){
      const res = await customerService.list()
      if (res.succes) {
        setListCustomer(res.data)
      }
    }

    fetchDataCustomer();

  },[])

  const onClickDelete = (data) => {

    swal({
      title: "Are you sure you to delete this?",
      icon: "warning",
      buttons: true,
      dangerMode: true,
    })
    .then((willDelete) => {
      if (willDelete) {
        setDeleteCustomer(data)
      }
    });

  }

  const setDeleteCustomer = async (data) => {

    console.log(data);
    console.log(data.i);
    const item = data.item
    const res = await customerService.delete(item.id)
    if (res.success) {
      const newList = listCustomer
      newList.splice(data.i,1)
      setListCustomer(newList);
      setMessageDelete("The customer "+data.item.name+" has been deleted!")
    }
    else {
      console.log(res);
    }

  }

  return (
    <section>

      {
        messageDeleted&&
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
           {messageDeleted}.
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true" onClick={()=>setMessageDelete(null)}>&times;</span>
          </button>
        </div>
      }
      <table class="table">
        <thead class="thead-dark table-bordered">
          <tr>
            <th scope="col">#</th>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
            <th scope="col">Address</th>
            <th scope="col">Phone</th>
            <th scope="col">Action</th>
          </tr>
        </thead>
        <tbody>

          {
            listCustomer.map((item,i)=>{
              return(
                <tr>
                  <th scope="row">{item.id}</th>
                  <td>{item.name}</td>
                  <td>{item.email}</td>
                  <td>{item.address}</td>
                  <td>{item.phone}</td>
                  <td>
                    <Link to={"/customer/edit/"+item.id} class="btn btn-light"> Edit </Link>
                    <a onClick={()=>onClickDelete({ item, i })}
                    href="#" class="btn btn-danger"> Delete </a>
                  </td>
                </tr>
              )
            })
          }

        </tbody>
      </table>
    </section>
  )
}

export default List;

Services

src/views/js/services/Customer.js

const baseUrl = "http://localhost:3000/api/customer"
import axios from "axios";
const customer = {};

 customer.delete = async (id) => {
  const urlDelete = baseUrl+"/delete/"+id
  const res = await axios.delete(urlDelete)
  .then(response=>{ return response.data; })
  .catch(error=>{ return error; })
  return res;
}
 
export default customer

Deja una respuesta

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