CodeIgniter – Backend
Route
$routes->get('/api/customer/list','CustomerController::list');
Controller
<?php namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\CustomerModel;
class CustomerController extends Controller
{
// .... //
// add function for list
public function list()
{
try {
$data = $this->customer->findAll();
$response['data'] = $data;
$response['success'] = true;
$response['message'] = "Successful load";
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
import
import axios from "axios"
import { Link } from "react-router-dom";
state
constructor()
{
super()
this.state = {
listCustomer:[]
}
}
ComponentDidMount
componentDidMount()
{
axios.get("http://localhost:8080/api/customer/list")
.then(response=>{
console.log(response.data);
this.setState({listCustomer:response.data.data})
})
.catch(error=>{
alert("Error ==>"+error)
})
}
render
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.listCustomer.map((data)=>{
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 class="btn btn-outline-info" to={"/customer/edit/"+data.id}>Edit</Link>
<a href="#" class="btn btn-danger"> Delete </a>
</td>
</tr>
)
})
}
</tbody>
</table>
</section>
)
}