From 349d195c2bd1b9af4f8933d66248fe9ec35df54b Mon Sep 17 00:00:00 2001 From: Mrinmayee Rane Date: Fri, 4 Apr 2025 15:53:39 -0400 Subject: [PATCH] Update App.js I tried to add the code we had on the last part of the video, what we saw in video did not work and threw error, because the totalPages was evaluating to a float, I just used ceil there. --- .../pagination/src/App.js | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/reactjs-interview-questions/pagination/src/App.js b/reactjs-interview-questions/pagination/src/App.js index ce8c570..9e6441c 100644 --- a/reactjs-interview-questions/pagination/src/App.js +++ b/reactjs-interview-questions/pagination/src/App.js @@ -4,24 +4,26 @@ import './App.css'; function App() { const [products, setProducts] = useState([]) const [page, setPage] = useState(1) + const [totalPages, setTotalPages] = useState(0); + useEffect(() => { const fetchProducts = async () => { - const res = await fetch(`https://dummyjson.com/products?limit=100`) + const res = await fetch(`https://dummyjson.com/products?limit=10&skip=${(page - 1) * 10}`) const data = await res.json() console.log(data); if (data && data.products) { - setProducts(data.products) + setProducts(data.products); + setTotalPages(Math.ceil(data.total / 10)); // this has to be integer so that we are able to generate a valid array } } - - useEffect(() => { + fetchProducts() - }, []) + }, [page]) const selectPageHandler = (selectedPage) => { - if (selectedPage >= 1 && selectedPage <= products.length / 10 && selectedPage !== page) { + if (selectedPage >= 1 && selectedPage <= totalPages && selectedPage !== page) { setPage(selectedPage) } } @@ -29,7 +31,7 @@ function App() { return (
{products.length > 0 &&
- {products.slice(page * 10 - 10, page * 10).map((prod) => { + {products.map((prod) => { return {prod.title} {/* alt is imp */} @@ -42,11 +44,11 @@ function App() { {products.length > 0 &&
selectPageHandler(page - 1)} className={page > 1 ? "" : "pagination__disable"}>◀ - {[...Array(products.length / 10)].map((_, i) => { + {[...Array(totalPages)].map((_, i) => { return selectPageHandler(i + 1)}>{i + 1} })} - selectPageHandler(page + 1)} className={page < products.length / 10 ? "" : "pagination__disable"}>▶ + selectPageHandler(page + 1)} className={page < totalPages ? "" : "pagination__disable"}>▶
}
);