Tutorial CRUD API Rest – CodeIgniter 4 & React.js #8 Delete

CodeIgniter – Backend

Route

$routes->delete('api/customer/delete/(:num)','CustomerController::delete/$1');

Controller

<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\CustomerModel;

class CustomerController extends Controller
{
 // .... //

 // add function for delete 
  public function delete($id)
  {
    try {
      // $res = $this->customer->where("id",$id)->delete();
      $res = $this->customer->delete($id);
  		$response['res'] = $res;
  		$response['success'] = true;
  		$response['message'] = "Successful delete";
  		return json_encode($response);
    }
    catch (\Exception $e) {
      $response['success'] = false;
      $response['message'] = $e->getMessage();
      return json_encode($response);
    } 
  }

}

React.js – Frontend

List

app/components/src/customer/List.js

Button

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

onClickDelete

onClickDelete(i,id){
    var yes = confirm("are you sure to delete this item?");
    if (yes == true) {
      const urlDelete = "http://localhost:8080/api/customer/delete/"+id
      axios.delete(urlDelete)
      .then((response)=>{
        const res = response.data
        if (res.success) {
          alert(res.message)
          const list = this.state.listCustomer
          list.splice(i,1)
          this.setState({listCustomer:list})
        }
      })
      .catch(error=>{
        alert("Error ==> "+error)
      })
    }
  }

Un comentario en «Tutorial CRUD API Rest – CodeIgniter 4 & React.js #8 Delete»

  1. Thank you for the tutorials – they have been helpful.

    You should modify the render method in List.js to add the second parameter «i» to the function that builds the table:

    this.state.listCustomer.map((data, i)

    This code assumes that it exists, but you do not include it in your text examples.

Deja una respuesta

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