0

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?

Sebastian
  • 37
  • 5
  • 1
    this question might have been answered several times. state is updated asynchronously so you should use `useEffect` with the state in the dependency array to do something when the state changes. – Ramesh Reddy Dec 12 '20 at 19:21
  • Yes, i saw this issue, but i did not how to deal with. But I solved this problem, thank you – Sebastian Dec 12 '20 at 19:48

0 Answers0