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"}>▶
}
);