Tartalomjegyzék

< React

React - Szolgáltatás

Projekt készítése

npx create-react-app app01
code app01

api.js szolgáltatás

npm install axios
src/services/api.js
import axios from 'axios';
 
export const getPost = () => {
    return axios.get(`https://jsonplaceholder.typicode.com/todos`);
}

Employees.js

Vezessük be a employeeList objektumot:

src/pages/Emplyoees.js
import { useState } from "react";
 
const Employees = () => {
    const [employeeList, setEmployeeList] = useState([]);
 
    return (
    <div class="container">
        <h1>Dolgozók</h1>        
    </div>
    );
};
 
export default Employees;

Kérjük le a dolgozók adatait:

src/pages/Emplyoees.js
import { useEffect, useState } from "react";
import { getEmployees } from "../services/api";
 
const Employees = () => {
    const [employeeList, setEmployeeList] = useState([]);
 
    useEffect(() => {
        getEmployees().then(res => setEmployeeList(res.data))
    }, []);
 
    return (
    <div class="container">
        <h1>Dolgozók</h1>        
    </div>
    );
};
 
export default Employees;

A get() metódus egy Promise-t ad vissza, így futtatjuk rajta a then() függvényt.

Rendereljük a táblázatot:

src/pages/Employees.js
import { useEffect, useState } from "react";
import { getEmployees } from "../services/api";
 
const Employees = () => {
    const [employeeList, setEmployeeList] = useState([]);
 
    useEffect(() => {
        getEmployees().then(res => setEmployeeList(res.data))
    }, []);
 
    return (
    <div class="container">
        <h1>Dolgozók</h1>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Név</th>
                    <th>Település</th>
                    <th>Fizetés</th>
                </tr>
            </thead>
            <tbody>
                {employeeList.map(emp => (
                    <tr key={emp.id}>
                        <td>{emp.id}</td>
                        <td>{emp.name}</td>
                        <td>{emp.city}</td>
                        <td>{emp.salary}</td>
                    </tr>
                ))}
            </tbody>
        </table>
    </div>
    );
};
 
export default Employees;