Рефакторинг компонента ProductList
This commit is contained in:
@@ -5,21 +5,66 @@ import ProductCard from '../card'
|
|||||||
|
|
||||||
const ProductList = () => {
|
const ProductList = () => {
|
||||||
const [products, setProducts] = React.useState([])
|
const [products, setProducts] = React.useState([])
|
||||||
|
const [loading, setLoading] = React.useState(true)
|
||||||
const getProducts = async () => {
|
const [error, setError] = React.useState(null)
|
||||||
const response = await fetch('http://localhost:8000/products')
|
|
||||||
const data = await response.json()
|
|
||||||
setProducts(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
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()
|
getProducts()
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <div className={styles.loading}>Загрузка продуктов...</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<div className={styles.error}>
|
||||||
|
<p>Ошибка при загрузке продуктов: {error}</p>
|
||||||
|
<button onClick={() => window.location.reload()}>
|
||||||
|
Попробовать снова
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ul className={styles.list}>
|
<ul className={styles.list}>
|
||||||
{products.map(product => (
|
{products.map(product => (
|
||||||
<li>
|
<li key={product.id}>
|
||||||
<ProductCard {...product} />
|
<ProductCard {...product} />
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|||||||
Reference in New Issue
Block a user