Search code examples
javascriptreactjsfiltering

filter the listed items according to their Categories in Reactjs


i have been suffering to get the items' data listed according to their categories

i don't know what am I doing wrong.

so basically, I have data coming from a bearer token API and it is listed successfully on the screen but I want as a second step to list according to their categories. there are five categories and more than 60 items.

here is my code:

  const [filterList, setFilterList] = useState("all");
  const [newProduct, setNewProduct] = useState(products);

  // filtering data by category

  useEffect(() => {
    let isValidScope = true;

    const fetchData = async () => {
      // pass filterList in fetch to get products for the selected category ??
      // pass parameters to fetch accordingly

      const res = await fetch(
        "https://myapi-api.herokuapp.com/api/categories/",
        {
          method: "GET",
          headers: {
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      if (!isValidScope) {
        return;
      }

         setNewProduct(res);
    };

    fetchData();

    return () => {
      isValidScope = false;
    };
  }, [filterList]);



function onFilterValueSelected(filterValue) {
    setFilterList(filterValue);
  }
  let filteredProductList = newProduct?.filter((product) => {
    // should return true or false

    // option 2 if product has a category property
    return product.category === filterList;
    // existing code
    if (filterList === "electronics") {
      return product.electronics == true;
    } else if (filterList === "clothing") {
      return product.clothing === true;
    } else if (filterList === "accsessories") {
      return product.accsessories === true;
    } else if (filterList === "furniture") {
      return product.furniture === true;
    } else if (filterList === "hobby") {
      return product.hobby === true;
    } else {
      // here dont return truthy
      return false;
    }
  });

Solution

  • You could fetch all of them once when the component mounts and them filter them on every render based on the selected filter instead of fetching products everytime in useEffect when filter changes.

    const [filterCategory, setFilterCategory] = useState("");
       
    function onFilterValueSelected(filterValue) {
        setFilterCategory(filterValue);
      }
    
      let filteredProductList = newProduct?.filter((product) => {
        return product.category === filterCategory;     
      });