From 287bdfebf5bef3d7cfaeea590db5fdc6900f77fe Mon Sep 17 00:00:00 2001 From: kosipov Date: Wed, 9 Apr 2025 19:46:51 +0300 Subject: [PATCH] add example with fetch api values --- src/api/api.js | 71 +++++++++++++++++++++++- src/components/Layout.jsx | 11 +++- src/components/services/ordersService.js | 13 +---- src/pages/Home.jsx | 14 +++-- src/pages/Login.jsx | 7 ++- 5 files changed, 93 insertions(+), 23 deletions(-) diff --git a/src/api/api.js b/src/api/api.js index 36d2e92..e64018b 100644 --- a/src/api/api.js +++ b/src/api/api.js @@ -1,9 +1,40 @@ +const tableValues = ` +[ + { + "_id": "67f6a400786730af342903c1", + "index": 0, + "guid": "ee826e91-aeda-4bc0-8251-93b5612c11ca", + "isActive": false, + "balance": "$3,449.04", + "picture": "http://placehold.it/32x32", + "age": 39 + }, + { + "_id": "67f6a4007b16530a27defd6c", + "index": 1, + "guid": "9c14ae69-7bd0-43d1-bb50-9ff4af60f032", + "isActive": false, + "balance": "$2,188.94", + "picture": "http://placehold.it/32x32", + "age": 23 + }, + { + "_id": "67f6a4007198cd74501f622a", + "index": 2, + "guid": "17b72c5b-89f8-4f3d-92e7-b9c5756a065d", + "isActive": false, + "balance": "$3,003.92", + "picture": "http://placehold.it/32x32", + "age": 34 +}]`; export const sendOrderData = async (formData) => { try { + const token = getAuth(); const response = await fetch('http://localhost:3000/request', { method: 'POST', headers: { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${token}` }, body: JSON.stringify(formData) }); @@ -17,4 +48,42 @@ export const sendOrderData = async (formData) => { console.log(error); throw error; } +} + +export const authApi = (login, password) => { + return 'asdjasjdklasjdloiqee2r724eu23e98e2398equ34983yq89eu2398q3ye932dioq3eoi'; +} + +export const getAuth = () => { + const token = localStorage.getItem('token'); + + if (!token) { + throw new Error('Токен не найден'); + } + + return token +} + +export const fetchServiceItems = () => { + getAuth(); + return new Promise((resolve) => { + setTimeout(() => { + resolve([ + { id: 1, techName: "Принтер", createdAt: "2025-01-10", status: "done" }, + { id: 2, techName: "Ноутбук", createdAt: "2024-01-10", status: "issued" }, + { id: 3, techName: "Смартфон Vivo", createdAt: "2025-02-10", status: "in_progress" }, + { id: 4, techName: "Повербанк", createdAt: "2024-11-10", status: "waiting" }, + { id: 5, techName: "Монитор Samsung", createdAt: "2025-03-01", status: "waiting_details" }, + { id: 6, techName: "Компьютер Эльбрус", createdAt: "2025-02-15", status: "accept1" } + ]) + }, 5000) + }) +}; + + +export const fetchServiceItemJson = () => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(JSON.parse(tableValues)) + })}); } \ No newline at end of file diff --git a/src/components/Layout.jsx b/src/components/Layout.jsx index 5d01d99..344e4a6 100644 --- a/src/components/Layout.jsx +++ b/src/components/Layout.jsx @@ -2,14 +2,21 @@ import { Link } from "react-router-dom" import "./Layout.css" export const Layout = ({ children }) => { + const checkAuth = () => { + const token = localStorage.getItem('token'); + if (!token) { + return false; + } + return true; + } return (

Сервис

diff --git a/src/components/services/ordersService.js b/src/components/services/ordersService.js index e341bce..6670e9c 100644 --- a/src/components/services/ordersService.js +++ b/src/components/services/ordersService.js @@ -1,15 +1,4 @@ -const fetchServiceItems = () => { - return new Promise((resolve) => { - setTimeout(() => {resolve([ - { id: 1, techName: "Принтер", createdAt: "2025-01-10", status: "done" }, - { id: 2, techName: "Ноутбук", createdAt: "2024-01-10", status: "issued" }, - { id: 3, techName: "Смартфон Vivo", createdAt: "2025-02-10", status: "in_progress" }, - { id: 4, techName: "Повербанк", createdAt: "2024-11-10", status: "waiting" }, - { id: 5, techName: "Монитор Samsung", createdAt: "2025-03-01", status: "waiting_details" }, - { id: 6, techName: "Компьютер Эльбрус", createdAt: "2025-02-15", status: "accept1" } - ])}, 5000) - }) -}; +import { fetchServiceItems } from "../../api/api"; const RU_STATUSES = { done: "Готово", diff --git a/src/pages/Home.jsx b/src/pages/Home.jsx index 423875a..50814d2 100644 --- a/src/pages/Home.jsx +++ b/src/pages/Home.jsx @@ -1,20 +1,21 @@ import { useState } from "react"; -import {getServiceItemsForRender} from '../components/services/ordersService' +import { getServiceItemsForRender } from '../components/services/ordersService' import { useEffect } from "react"; -import { CircularProgress } from "@mui/material"; -import {Layout } from '../components/Layout' -import {Table } from '../components/Table' +import { Alert, CircularProgress } from "@mui/material"; +import { Layout } from '../components/Layout' +import { Table } from '../components/Table' const HEADS = [ 'Номер заказа', 'Наименование техники', 'Дата', 'Статус' - ] +] export const Home = () => { const [serviceItems, setServiceItems] = useState([]); const [loading, setLoading] = useState(true); + const [isAuthError, setIsAuthError] = useState(false); useEffect(() => { const getData = async () => { @@ -23,6 +24,7 @@ export const Home = () => { setServiceItems(data); } catch (error) { console.log(error); + setIsAuthError(true); } finally { setLoading(false); } @@ -39,7 +41,7 @@ export const Home = () => { return ( + () => isAuthError ? {'Пользователь не авторизован'} :
} /> ) } \ No newline at end of file diff --git a/src/pages/Login.jsx b/src/pages/Login.jsx index 638dec5..db85a22 100644 --- a/src/pages/Login.jsx +++ b/src/pages/Login.jsx @@ -1,9 +1,12 @@ import { Alert, Button, Stack, TextField } from "@mui/material" import { Layout } from "../components/Layout" import { useState } from "react"; +import { authApi } from "../api/api"; +import { useNavigate } from "react-router-dom"; export const Login = () => { const error = null; + const navigate = useNavigate(); const [formData, setFormData] = useState({ login: null, password: null @@ -14,9 +17,9 @@ export const Login = () => { }; const handleSubmit = (e) => { //здесь что-то типа обращения к серверу - const token = 'asdjasjdklasjdloiqee2r724eu23e98e2398equ34983yq89eu2398q3ye932dioq3eoi' + const token = authApi('user1', 'pass'); localStorage.setItem('token', token); - // todo: здесь продолжить с логикой отображения интерфейса + navigate('/'); }; return { return