I am trying to make a shop website, and I need filters: by brand and by price. To do that I need to use the functions write below.
const ProductContextProvider = ({ children }) => {
const [productsCategory, setProductCategory] = useState();
const [filterBrands, setFilterBrands] = useState();
const [filterPrice, setFilterPrice] = useState();
function getProductCategory(category) {
const productFromCategory = data.filter(
(product) => product.type === category
);
setProductCategory(productFromCategory);
return productFromCategory;
}
const filterByPrice = (min, max, category) => {
setFilterPrice([min, max]);
componentFilter(category);
};
const filterByBrand = (brand, category) => {
setFilterBrands(brand);
componentFilter(category);
};
const componentFilter = (category) => {
let filteredProduct;
filteredProduct = getProductCategory(category);
console.log({ filterPrice }); //problem occures here,show filterPrice=undefined
if (filterBrands) {
filteredProduct = filteredProduct.filter(
(prod) => prod.brand === filterBrands
);
}
if (filterPrice) {
filteredProduct = filteredProduct.filter((prod) => {
if (
(prod.price > Number(filterBrands[0])) &
(prod.price < Number(filterBrands[1]))
) {
return prod;
}
});
}
setProductCategory(filteredProduct);
};
return (
<ProductContext.Provider
value={{
}}
>
{children}
</ProductContext.Provider>
);
};
export default ProductContextProvider;
So when I execute a function for example a "filterByPrice" function, I set setFilterPrice and pass min and max value, but the next function execute componentFilter and the value filterPrice is not updated (as I marked above). I know that if I use useState the value will update when the component re-render. But what can I do in this case, to have the current value?