I want to filter the dealer on the basis of selected rating checkboxes value. When user select the one star ,want the dealers with one star only and if user selects the two star, then dealers with two star and one star. I am storing the checboxes value using useState and getting an array.How to unfiltered data if the checkbox that is selected is unchecked.
const [dealersData, setDealersData] = useState<Dealer[]>([]);
const [filteredData, setFilteredData] = useState<Dealer[]>(dealersData);
const [activeFilter, setactiveFilter] = useState<number[]>([]);
const onFilterChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
if(e.target.checked){
let data = activeFilter;
activeFilter.push(Number(e.target.value));
setactiveFilter(data);
}else{
let data=activeFilter.filter((value) =>(Number(e.target.value) != value));
console.log('inactivedata',data);
setactiveFilter(data);
console.log(activeFilter);
}
let ratingResult: React.SetStateAction<Dealer[]> = [];
activeFilter.forEach((item)=>{
switch(item){
case 1:
ratingResult= dealersData.filter((dealerData) =>{
return dealerData.dealer_history.some(dataItem =>(dataItem.rating >= 1 && dataItem.rating < 5));
});
break;
case 2:
ratingResult= dealersData.filter((dealerData) =>{
return dealerData.dealer_history.some(dataItem =>(dataItem.rating >= 2 && dataItem.rating < 5));
});
break;
case 3:
ratingResult= dealersData.filter((dealerData) =>{
return dealerData.dealer_history.some(dataItem =>(dataItem.rating == 3 && dataItem.rating < 5));
});
break;
case 4:
ratingResult= dealersData.filter((dealerData) =>{
return dealerData.dealer_history.some(dataItem =>(dataItem.rating == 4 && dataItem.rating < 5));
});
break;
case 5:
ratingResult= dealersData.filter((dealerData) =>{
return dealerData.dealer_history.some(dataItem =>(dataItem.rating == 5));
});
break;
};
});
setFilteredData(ratingResult);
}
<div><Checkbox color="primary" value="5" onChange={(e) => onFilterChange(e)} /><Rating name="size-small" size="small" value={5} readOnly /></div>
<div><Checkbox color="primary" value="4" onChange={(e) => onFilterChange(e)} /><Rating name="size-small" size="small" value={4} readOnly /></div>
<div><Checkbox color="primary" value="3" onChange={(e) => onFilterChange(e)} /><Rating name="size-small" size="small" value={3} readOnly /></div>
<div><Checkbox color="primary" value="2" onChange={(e) => onFilterChange(e)} /><Rating name="size-small" size="small" value={2} readOnly /></div>
<div><Checkbox color="primary" value="1" onChange={(e) => onFilterChange(e)} /><Rating name="size-small" size="small" value={1} readOnly /></div>
export interface Dealer{
dealer_id:number,
name:string,
mobile:number,
email:string,
gst_no:string,
locality:string,
city:string,
state:string,
pincode:string,
vehicle_type_id:number,
Vehicletype:{
vehicle_type:string
};
Services:[
{
discription:string,
cost:number
}
],
dealer_history:[
{
rating:number,
comments:string
}
]
}