Skip to content

Commit 40a7fce

Browse files
fixed totalItems by extracting direct from json obj (data.items)/ improve pagination by putting conditional and use effect
1 parent 3316e43 commit 40a7fce

File tree

3 files changed

+16
-8
lines changed

3 files changed

+16
-8
lines changed

src/features/product/components/ProductList.js

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,11 @@ export default function ProductList() {
109109
dispatch(fetchProductsByFiltersAsync({ filter, sort, pagination }));
110110
}, [dispatch, filter, sort, page]);
111111

112+
useEffect(() => {
113+
//page always come to first if there is change in totalItems and sorting
114+
setPage(1);
115+
}, [totalItems, sort]);
116+
112117
return (
113118
<div className="bg-white">
114119
<div>
@@ -464,15 +469,18 @@ function Pagination({ page, setPage, handlePage, totalItems }) {
464469
<div className="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
465470
<div>
466471
<p className="text-sm text-gray-700">
467-
Showing-
468-
{/* (3-1) * 6 + 1 =13 */}
472+
Showing {/* (3-1) * 6 + 1 =13 */}
469473
<span className="font-medium">
470474
{(page - 1) * ITEMS_PER_PAGE + 1}
471475
</span>{" "}
472476
{/* 3 * 6 = 18 */}
473-
to <span className="font-medium">
474-
{page * ITEMS_PER_PAGE}{" "}
475-
</span> of <span className="font-medium">{totalItems}</span> results
477+
to{" "}
478+
<span className="font-medium">
479+
{page * ITEMS_PER_PAGE > totalItems
480+
? totalItems
481+
: page * ITEMS_PER_PAGE}{" "}
482+
</span>{" "}
483+
of <span className="font-medium">{totalItems}</span> results
476484
</p>
477485
</div>
478486
<div>

src/features/product/productAPI.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export function fetchProductsByFilters(filter, sort, pagination) {
5050
"http://localhost:8080/products?" + queryString
5151
);
5252
const data = await response.json();
53-
const totalItems = await response.data.items;
54-
resolve({ data: { products: data, totalItems: totalItems } });
53+
54+
resolve({ data: { products: data.data, totalItems: data.items } });
5555
});
5656
}

src/features/product/productSlice.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export const fetchProductsByFiltersAsync = createAsyncThunk(
2121
const response = await fetchProductsByFilters(filter, sort, pagination);
2222

2323
// The value we return becomes the `fulfilled` action payload
24-
return response.data.data; //pagination array comes from data array!!!!!
24+
return response.data; //pagination array comes from data array!!!!! data.data:[id:2]
2525
}
2626
);
2727

0 commit comments

Comments
 (0)