Created
May 30, 2025 13:38
-
-
Save sunmeat/cd069fe11889b9fb529ac78f6ac13c3e to your computer and use it in GitHub Desktop.
useEffect + isLoading (образец, не запускать :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
import './App.css'; | |
function App() { | |
const [products, setProducts] = useState([]); | |
const [isLoading, setIsLoading] = useState(false); | |
const [error, setError] = useState(null); | |
useEffect(() => { | |
const fetchProducts = async () => { | |
setIsLoading(true); | |
try { | |
const response = await fetch('https://api.yoursite.com/products'); | |
if (!response.ok) throw new Error('Ошибка загрузки данных'); | |
const data = await response.json(); | |
setProducts(data); | |
} catch (err) { | |
setError(err.message); | |
} finally { | |
setIsLoading(false); | |
} | |
}; | |
fetchProducts(); | |
}, []); | |
if (isLoading) return <div>Загрузка...</div>; | |
if (error) return <div>Ошибка: {error}</div>; | |
return ( | |
<div className="container"> | |
<h1>Товары</h1> | |
<ul> | |
{products.map(product => ( | |
<li key={product.id}>{product.name}</li> | |
))} | |
</ul> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment