Tutorial CRUD API Rest – CodeIgniter 4 & React.js #7 Update

CodeIgniter – Backend

Route

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

Controller

<?php namespace App\Controllers;

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

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

 // add function for update 
  public function update($id)
  {
      try {
        $json = $this->request->getJSON();
        $update['name'] = $json->name;
        $update['email'] = $json->email;
        $update['phone'] = $json->phone;
        $update['address'] = $json->address;
        $res = $this->customer->update($id,$update);
        $response['success'] = true;
        $response['message'] = "Successful update";
        return json_encode($response);
      } catch (\Exception $e) {
        $response['success'] = false;
        $response['message'] = $e->getMessage();
        return json_encode($response);
      }
  }

}

React.js – Frontend

Edit

app/components/src/customer/Edit.js

onClickUpdate

  onClickUpdate()
  {
    const id = this.state.id
    const baseUrl = "http://localhost:8080/api/customer/update/"+id

    const datapost = {
      name: this.state.fieldName,
      email: this.state.fieldEmail,
      phone: this.state.fieldPhone,
      address: this.state.fieldAddress
    }
 
    axios.put(baseUrl,datapost)
    .then(response=>{
      alert(response.data.message)
    })
    .catch(error=>{
      alert("Error 500 "+error)
    })
  }

Deja una respuesta

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