I got this code for getting page and products limit in backend:
getProductsPagination: async (_, { page }) => {
const skip = (page - 1) * 12;
const limit = 12;
const total = await Product.countDocuments();
let query = Product.find({});
query = query.skip(skip).limit(limit);
const pages = Math.ceil(total / limit);
const result = await query;
return { products: result, numOfPages: pages };
},
I am filtering products from the frontend and everythings work great but the thing is only in page 3 I have products with the color pink, so If I am at page 1 and trying to filter the color pink It will not display these products. I will have to jump to page 3 for that. This is even possible to make to work only in frontend?
front end code:
const { data, loading, error } = useQuery(GET_PRODUCTS_PAGINATION, {
variables: { page },
});
const products = data?.getProductsPagination?.products;
const numOfPages = data?.getProductsPagination?.numOfPages;
useEffect(() => {
setFilteredProducts(products);
const applySort = (filteredList) => {
return sort.length <= 0
? filteredList
: sort.includes('price-highest')
? filteredList?.slice().sort((a, b) => b.price - a.price)
: sort.includes('top-rated')
? filteredList?.slice().sort((a, b) => b.rates - a.rates)
: filteredList?.slice().sort((a, b) => a.price - b.price);
};
const sizePredicate = (product) => {
return size.length === 0 || product.size.includes(Number(...size));
};
const brandPredicate = (product) => {
return brand.length === 0 || product.brand.includes(...brand);
};
const pricePredicate = (product) => {
return (
price.length === 0 ||
(product.price > price[0][0] && product.price < price[0][1])
);
};
const colorPredicate = (product) => {
return color.length === 0 || product.color.includes(...color);
};
setFilteredProducts((filteredList) =>
applySort(
filteredList
?.filter(sizePredicate)
?.filter(brandPredicate)
?.filter(pricePredicate)
?.filter(colorPredicate)
)
);
}, [products, sort, price, brand, size, test, color, page]);