ReactJS Hooks + Laravel 8 + MySQL + API REST CRUD #4 List

Laravel – Backend

Controller
app/Http/Controllers/EmployeeController.php
<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Role;
use App\Models\Employee; 

class EmployeeController extends Controller
{
    // ... ///

    public function list(){

      try {

        $data = Employee::with("role")->get();
        $response['data'] = $data;
        $response['success'] = true;

      } catch (\Exception $e) {
        $response['message'] = $e->getMessage();
        $response['success'] = false;
      }
      return $response;

    }
}

Route
routes/api.php
Route::get('/employee/list', 'App\Http\Controllers\API\[email protected]');

React – Frontend

Component

List.js
resources/js/components/employee/List.js
import React, { useEffect, useState } from 'react';

import employeeServices from "../../services/Employee"

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

function List(){

  const [ listEmployee, setListEmployee ] = useState([]);

  useEffect(()=>{

    async function fetchDataEmployee(){
      const res = await employeeServices.listEmployee();
      console.log(res.data);
      setListEmployee(res.data)
    }

    fetchDataEmployee();

  },[])

  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>

        {
          listEmployee.map((item)=>{
            return(
              <tr>
                <th scope="row">{item.id}</th>
                <td>{item.name_lastname}</td>
                <td>{item.email}</td>
                <td>{item.direction}</td>
                <td>{item.phone}</td>
                <td>
                  <Link class="btn btn-outline-info" to={"/employee/edit/"+item.id}>Edit</Link>
                  <a href="#" class="btn btn-danger"> Delete </a>
                </td>
              </tr>
            )
          })
        }
        
        </tbody>
      </table>
    </section>
  )
}

export default List;

Services

Employee.js
resources/js/components/Mainresources/js/services/Employee.js
const baseUrl = "http://localhost:8000/api/employee"
import axios from "axios";
const employee = {};

//...//

employee.listEmployee = async () => {
  const urlList = baseUrl+"/list"
  const res = await axios.get(urlList)
  .then(response=>{ return response.data; })
  .catch(error=>{ return error; })
  return res;
}


export default employee

Deja una respuesta

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