This might be very simple JS, but can't seem to get my head around it.
The nextPage
and prevPage
functions/buttons seem to call the loadNewProducts
function before updating the pageNum state.
When i click 'next' it changes state of pageNum to '2' but loads page 1. Then i click previous and it changes state of pageNum to '1' but loads page 2...
const [pageNum, setPage] = useState(1);
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(false);
const loadNewProducts = async () => {
setLoading(true);
const req = await fetch(`/api/nhan/${pageNum}`);
const json = await req.json();
setProducts(json);
console.log(products);
setLoading(false);
};
const nextPage = () => {
setPage(pageNum + 1);
loadNewProducts();
};
const prevPage = () => {
setPage(pageNum - 1);
loadNewProducts();
};
if (pageNum <= 0) {
setPage(1);
}
return (
<>
<NavBar />
<div>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<button onClick={loadNewProducts}> Load </button>
<button onClick={prevPage}>Previous</button>
<button onClick={nextPage}>Next</button> Page {pageNum}
{loading && <div>LOADING</div>}
<NewProducts newProducts={products} />
</div>
</>
);
}