GeethikaG
Reactiflux4y ago
43 replies
Geethika

Set.prototype.has() returns false even when element is present

I learning React.js, and would like to implement filter functionality based on the checkboxes selected. I am referring to this solution >> https://codepen.io/trezy/pen/GROLXqo

So far, I have the following implementation:
Code for filter function:

const [state, setState] = useState({
    products: cspaces,
    filters: new Set(),
  })

const handleFilterChange = useCallback(event => {
    setState(previousState => {
      let filters = new Set(previousState.filters)
      let products = cspaces
     .....
        products = products.filter(product => {
           return filters.has(
            product.attributes.propertySubType.split(" ").forEach(element => {
              if((element.match(/Shop|Office|Showroom/))!=null) 
             console.log("element ", element)
          return element
         ....
        console.log("products ",products)
      
      }
      return {
        filters,
        products,
      }
    })
  }, [setState])


The checkboxes:

...

{data.propertytype.items.map((tag, index) => (
                      <li key={tag.value}>
                        <Form.Check
                          type="checkbox"
                          value={tag.label}
                          onChange={handleFilterChange}
                        />
                      </li>
...

And my component using the filtered data,

...
{state.products.map((filteredListItems, id) => (
                      <Col
                        key={id}
                        sm="6"
                        lg="4"
                        className="mb-5 hover-animate"
                      >
                        <CardCspace data={filteredListItems} />
                      </Col>
                    ))}
...

cspaces is holding the data fetched from API. The value of state.products returned by filtering function is always empty. I would like to match with the categories "Shop", "Office", or "Showroom" which are displayed in checkboxes.

Sample console output:
v8.PNG
Solution
filters.some(filter => product.attributes.propertySubType.split(" ").includes(filter))
Was this page helpful?