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 (