import { useEffect, useState } from 'react';
const mockProducts = [
{ id: 1, title: 'MacBook Pro', price: 2500 },
{ id: 2, title: 'iPhone 15', price: 1200 },
{ id: 3, title: 'AirPods Pro', price: 250 },
];
const getProducts= ()=> mockProducts.json()
export function Products() {
const [scroll, setScroll] = useState();
const [items, setItems] = useState(false);
const [loading, setLoading] = useState(false);
async function loadProducts() {
setLoading(true);
getProducts().then(data => setItems(data));
setLoading(false);
}
// remove scroll clear on items change
useEffect(
() => {
return () => window.removeEventListener('scroll', () => setScroll(window.scrollY));
},
[items]
);
async function handleRefresh() {
setLoading(true);
const data = await loadProducts();
setItems(data);
setLoading(false);
}
if (loading) { // move under useEffect
return <p>Loading...</p>;
}
useEffect(() => {
window.addEventListener('scroll', () => setScroll(window.scrollY));
// extract to special hook all api logic
// add async/await processing
const data = loadProducts();
setItems(data);
// reset eventscroll
});
return (
<div>
<button onClick={handleRefresh}>Refresh</button>
{items.map(product => <div>{product.title}</div>)}
</div>
);
}/