Базовые сетевые запросы

This commit is contained in:
grinikita 2024-12-07 13:43:07 +03:00
parent 34e30fbaba
commit 0fe463e33a
4 changed files with 68 additions and 3 deletions

View File

@ -1,8 +1,45 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import Heading from '../../components/heading';
const ListPage = (): React.ReactElement => {
return <Heading>List Page New 2</Heading>;
const [error, setError] = useState<string>(null);
const [data, setData] = useState<Array<{ id: number; title: string; description: string }>>();
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const handle = async () => {
setIsLoading(true);
try {
const res = await fetch('/api/list');
const data = await res.json();
if (res.ok) {
setData(data);
} else {
setError(data.message);
}
} catch (e) {
setError(e.message);
} finally {
setIsLoading(false);
}
};
handle();
}, []);
return (
<>
<Heading>List Page New</Heading>
{isLoading && <div>Loading...</div>}
{error && <div>Произошла ошибка</div>}
{data?.map((item) => {
return (
<div key={item.id}>
{item.id}: {item.title} - {item.description}
</div>
);
})}
</>
);
};
export default ListPage;

View File

@ -1,3 +1,12 @@
const router = require('express').Router();
const listRouter = require('./list');
module.exports = router;
const delay =
(ms = 1000) =>
(req, res, next) => {
setTimeout(next, ms);
};
router.use(delay());
router.use('/list', listRouter);

View File

@ -0,0 +1,7 @@
[
{ "id": 1, "title": "title", "description": "description" },
{ "id": 2, "title": "title", "description": "description" },
{ "id": 3, "title": "title", "description": "description" },
{ "id": 4, "title": "title", "description": "description" },
{ "id": 5, "title": "title", "description": "description" }
]

12
stubs/api/list/index.js Normal file
View File

@ -0,0 +1,12 @@
const router = require('express').Router();
module.exports = router;
const data = require('./data/list.json');
router.get('/', (req, res) => {
res.send(data);
// res.status(500).send({
// message: 'Internal server error'
// });
});