Home > OS >  Why do my filters work separately from each other?
Why do my filters work separately from each other?

Time:03-06

I have two selections that are supposed to filter data, they work but separately, how do I make them filter data together?

When I click on the second select, it resets the data from the first one. They filter the same data array, so the result is new all the time, I don't understand how to filter an already filtered array

How do I make a joint filter?

 //filter data
  const [allData, setAllData] = useState<ICompanie[]>(companiesData);

  // status filter
  const handleStatusFilter = (status: string): void => {
    const filterData = companiesData.filter((item) => {
      if (item.status === status) {
        return item;
      }
    });

    setAllData(filterData);
  };

  // category filter
  const handleCategoriesFilter = (category: string): void => {
    const filterData = companiesData.filter((item) => {
      if (item.category === category) {
        return item;
      }
    });

    setAllData(filterData);
  };

CodePudding user response:

I believe You need to maintain the already selected filter value in the state variable. Please prefer the below code:

const [allData, setAllData] = useState<ICompanie[]>(companiesData);
const [filters, setFilters] = useState({});
    
                     //name = status/category
                     //value = actual value of filter
const handleFilter = (name:string, value:string) => {
      const filtersCopy = {...filters};
      filtersCopy[name] = value;

      const filtersKey = Object.keys(filtersCopy).filter((value)=>!!filtersCopy[value]);
        
      const filterData = companiesData.filter((item) => {
                  const filterCheck = []
                  filtersKey.forEach((value) => {
                    if(item[value] === filtersCopy[value]) {
                      filtercheck.push(value);
                    }
                  })
                  return filterCheck.length === filtersKey.length
       });

     setFilters(filtersCopy)
     setAllData(filterData);
}
      

CodePudding user response:

That happens because allData is const and when you invoke setAllData you always apply the filter from the immutable allData, and lose update. See if you want to expose filterData instead (e.g. turn allData to non const and assign filterData to it when you filter, maybe have a mechanism to restore the unfiltered original allData).

  • Related