AdonisJS + React Hooks – CRUD API REST #5 List

AdonisJS

Controller

app/Controllers/Http/CustomerController.js

'use strict'

const Customer = use('App/Models/Customer');

class CustomerController {

  /*  ...  */

  // ------- API REST --------------

  async list(){

    try {

      const data = await Customer.all()

      const response = {
        success: true,
        message: "load successful",
        data: data
      }
      return response;

    } catch (e) {

      const response = {
        success: false,
        message: e.message
      }
      return response;

    }

  }

}

module.exports = CustomerController

Route

start/routes.js

Route.group(()=>{

  /* ... */
  Route.get('customer/list',"CustomerController.list");
  
}).prefix('api');

ReactJS

Components

List

resources/js/components/customer/List.js

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

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

import { Link } from "react-router-dom";

function List(){

  const [ listCustomer, setListCustomer ] = useState([]);

  useEffect(()=>{

    async function fetchDataCustomer(){
      const res = await customerService.list();
      console.log(res.data);
      setListCustomer(res.data)
    }

    fetchDataCustomer();

  },[])

  return (
    <section>
      <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)=>{
            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 class="btn btn-outline-info" to={"/customer/edit/"+item.id}>Edit</Link>
                  <a href="#" class="btn btn-danger"> Delete </a>
                </td>
              </tr>
            )
          })
        }


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

export default List;

Service

resources/js/services/Customer.js

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

/* ...*/

customer.list = async () => {
  const urlList = baseUrl+"/list"
  const res = await axios.get(urlList)
  .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 *