CRUD – Spring Boot + ReactJS + API Rest + MySQL #9 Delete

Spring – Backend

Controller

src/main/java/com/tutofox/demo/controllers/EmployeeController.java

package com.tutofox.tutospring.controllers;
/.../
import org.springframework.web.bind.annotation.DeleteMapping;

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
	
  /.../
	
	@DeleteMapping(value="/delete/{id}")
	public Map<String, Object> update(@PathVariable("id") Integer id){
		
		HashMap<String, Object> response = new HashMap<String, Object>();
		
		try {  
			employeeRepository.deleteById(id);;
			response.put("message","Successful delete"); 
			response.put("success", true);
			return response; 
		} catch (Exception e) {
			response.put("message",e.getMessage()); 
			response.put("success", false);
			return response;
		}
		
	}

	 
}

ReactJS – Frontend

Services Employee

src/main/resources/js/components/services/Employee.js

const baseUrl = "http://localhost:8080/api/employee"
import axios from "axios";
const employee = {};

employee.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 employee

List

src/main/resources/js/components/employee/List.js

Button

<a  onClick={()=>this.onClickDelete(i,data.id)} 
  href="#" class="btn btn-danger"> Delete </a>

onClickDelete

async onClickDelete(i,id)
  {
    var yes = confirm("are you sure to delete this item?");
    if (yes === true){ 
      
      const res = await employeeServices.delete(id)

      if (res.success) {
        alert(res.message)
        const list = this.state.listEmployee
        list.splice(i,1)
        this.setState({listEmployee:list})
      }
      else{
        console.log(res); alert(JSON.stringify(res))
      } 
    }
  }

List.js – all source code

import React, { Component } from 'react';
import employeeServices from "../services/Employee"
import { Link } from "react-router-dom"

export default class List extends Component {

  constructor()
  {
    super()
    this.state = {
      listEmployee:[]
    }
  }

  async componentDidMount(){
    console.log("Mounted List");
    const res = await employeeServices.list()
    console.log(res);
    if (res.success) {
      this.setState({listEmployee:res.list})
    }
    else {
      alert("Error server ==>"+JSON.stringify(res))
    }
  }

  render() {
    return (
      <section>
        <table class="table">
          <thead class="thead-dark">
            <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>

            {
              this.state.listEmployee.map((data,i)=>{
                return(
                  <tr>
                    <th scope="row">{data.id}</th>
                    <td>{data.name}</td>
                    <td>{data.email}</td>
                    <td>{data.address}</td>
                    <td>{data.phone}</td>
                    <td>
                      <Link to={"/employee/edit/"+data.id} class="btn btn-light"> Edit </Link>
                      <a  onClick={()=>this.onClickDelete(i,data.id)}
                        href="#" class="btn btn-danger"> Delete </a>
                    </td>
                  </tr>
                )
              })
            }
          </tbody>
        </table>
      </section>
    )
  }

  async onClickDelete(i,id)
  {
    var yes = confirm("are you sure to delete this item?");
    if (yes === true){ 
      
      const res = await employeeServices.delete(id)

      if (res.success) {
        alert(res.message)
        const list = this.state.listEmployee
        list.splice(i,1)
        this.setState({listEmployee:list})
      }
      else{
        console.log(res); alert(JSON.stringify(res))
      } 
    }
  }
}

Deja una respuesta

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