npx create-react-app app01 code app01
npm install axios
import axios from 'axios'; export const getPost = () => { return axios.get(`https://jsonplaceholder.typicode.com/todos`); }
Vezessük be a employeeList objektumot:
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:
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:
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;