diff --git a/src/components/list/index.jsx b/src/components/list/index.jsx index e6db08e..2e6c0cf 100644 --- a/src/components/list/index.jsx +++ b/src/components/list/index.jsx @@ -5,21 +5,66 @@ import ProductCard from '../card' const ProductList = () => { const [products, setProducts] = React.useState([]) - - const getProducts = async () => { - const response = await fetch('http://localhost:8000/products') - const data = await response.json() - setProducts(data) - } + const [loading, setLoading] = React.useState(true) + const [error, setError] = React.useState(null) React.useEffect(() => { + let cancelled = false + + const getProducts = async () => { + try { + setLoading(true) + setError(null) + + const response = await fetch('http://localhost:8000/products') + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`) + } + + const data = await response.json() + + if (!cancelled) { + setProducts(data) + } + } catch (err) { + if (!cancelled) { + setError(err.message) + setProducts([]) + } + } finally { + if (!cancelled) { + setLoading(false) + } + } + } + getProducts() + + return () => { + cancelled = true + } }, []) + if (loading) { + return
Ошибка при загрузке продуктов: {error}
+ +