I Want to filter dealers data on the basis of min and max price range of slider change. I have am getting data dealers data using API and sliders min and max value in Handle change function. How to filters the dealers which have their service cost in the price range. There will be always single service in the array as user can select one service as of now and we are showing the dealers on the base of service selected.
const [dealersData, setDealersData] = useState<Dealer[]>([]);
const [filteredData, setFilteredData] = useState<Dealer[]>(dealersData);
const [value, setValue] = React.useState<number[]>([250, 1000]);
const handleChange = (event: Event, newValue: number | number[]) => {
setValue(newValue as number[]);
let result = [];
result = dealersData.filter((data) => {
return data.Services.filter(dataItem => (dataItem.cost >= value[0] && dataItem.cost <= value[1]));
});
setFilteredData(result);
};
axios.get<[]>(`/dealer/serviceType/${props.serviceData.id}/${props.Id}`)
.then((response: AxiosResponse) => {
setDealersData(response.data);
console.log(dealersData);
setLoading(true);
//setFilteredData(response.data);
})
<Slider getAriaLabel={() => 'Price'} value={value} onChange={handleChange} valueLabelDisplay="auto" getAriaValueText={valuetext} min={0} max={1000} />
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
}
]
}
CodePudding user response:
I believe the issue is with your use of filters here:
result = dealersData.filter((data) => {
return data.Services.filter(dataItem => (dataItem.cost >= value[0] && dataItem.cost <= value[1]));
});
The .filter()
function expects a boolean return value and will return all of the values in the array in which that predicate/boolean returns true. Filter itself doesn't return a boolean value, so this doesn't really make sense:
dealersData.filter((data) => {
// Remember, filter() returns a list of all items in the array that match the predicate.
// It does NOT return a boolean, so this always evaluates to true (as all arrays are truthy in JS)
return data.Services.filter();
});
Instead you'll probably want to use the .some()
or the .every()
function, depending on which one you need. .some()
returns true if any array value matches the predicate (aka. Any service is within the price range), while .every()
returns true if all array values matches the predicate (aka. All services area within the price range):
result = dealersData.filter((data) => {
return data.Services.some(dataItem => (dataItem.cost >= value[0] && dataItem.cost <= value[1]));
});