Home > database >  React filter() method not working with if/else
React filter() method not working with if/else

Time:06-21

I have an array of products that I get from the api example :

[{id: 1 , title: "TV" , category: "electronics"} {id: 2 , title: "Rigg" , category: "Jewelery"}]

where I map this products and show them to the homepage I want the user to be able to search by title. filter by category and sort by price. I am trying the search and the filter by category(electronics or jewelery) but it doesn't work

 products?.filter((prods) => {
              if (searchedInput === "") {
                return prods;
              } else if (
                prods.title
                  .toLocaleLowerCase()
                  .includes(searchedInput.toLocaleLowerCase())
              ) {
                return prods;
              } else if (categorySelected.electronics) {
                return prods.category === Category.Electronics;
              }
              else if (categorySelected.jewelery) {
                return prods.category === Category.Jewelery;
              }
            })
            .map((product) => {
              return (
                <ProductCard ...

Now the search works but the filter by category no. and if I remove the search filter and leave only the categories filter they work , but they don't work together. Maybe I messed up the if else. Any ideas?

CodePudding user response:

You put all conditions in else if so one condition is true then return that value not looking for the next one so you have to make all first in if conditions to check this.

CodePudding user response:

A couple notes:

  • filter iterates over each item and decides whether to filter or not (a boolean function), so instead of prods each item is just a product. And returning the item is the same as returning true.
  • You can combine all matching conditions into one to make it easier to read and prevent your if blocks from only matching one condition:
products?.filter(product => (
    searchedInput === "" ||
    product.title.toLocaleLowerCase().includes(searchedInput.toLocaleLowerCase()) || 
    categorySelected.electronics && product.category === Category.Electronics ||
    categorySelected?.jewelery && product.category === Category.Jewelery
))
  • Related