My sorting is working but sometimes my data doesnot change as I select the option no change occurs , I guess I am not using useEffect correctly So I want what am I doing wrong , I am very confused
const { data: property, isFetching, refetch } = useQuery(['PropertySearch', startDate, endDate, where, adultCount, childCount], propertyAvaibility, {
retry: false,
enabled: !!data
})
useEffect(() => {
const sortArray = type => {
const types = {
number_of_bars: 'number_of_bars',
starting_price: 'starting_price',
};
const sortProperty = types[type];
const sorted = property?.sort((a, b) => b[sortProperty] - a[sortProperty]);
setData(sorted);
};
sortArray(sortType);
}, [sortType]);
<select onChange={(e) => setSortType(e.target.value)} className="form-control">
<option value="number_of_bars">number_of_bars</option>
<option value="starting_price">starting_price</option>
</select>
{
property?.map((item) => (
<PropertyCard
key={item?.id}
title={item?.title}
image={item?.cover_image?.url}
location={item.address}
displayFooter={false}
displayButton={false}
rating={true}
item={item}
type={item?.brand_name}
link="property">
{item?.description?.slice(0, 150)}
</PropertyCard>
))
}
CodePudding user response:
I think your problem is you're using property?.map
which is always referred to your original list.
For a possible fix, you could modify it to data?.map
which is your sorted list.
And you also need to set a default value for data
const [data, setData] = useState(property); //`property` is from your fetched data
Full change can be
const { data: property, isFetching, refetch } = useQuery(['PropertySearch', startDate, endDate, where, adultCount, childCount], propertyAvaibility, {
retry: false,
enabled: !!data
})
const [data, setData] = useState(property); //set `property` as your default data
const [sortType, setSortType] = useState('rating');
useEffect(() => {
const sortArray = type => {
const types = {
number_of_bars: 'number_of_bars',
starting_price: 'starting_price',
};
const sortProperty = types[type];
const sorted = property?.sort((a, b) => b[sortProperty] - a[sortProperty]);
setData(sorted);
};
sortArray(sortType);
}, [sortType]);
const displayedData = data?.length ? data : property //check if data is available
<select onChange={(e) => setSortType(e.target.value)} className="form-control">
<option value="number_of_bars">number_of_bars</option>
<option value="starting_price">starting_price</option>
</select>
{
displayedData?.map((item) => ( //the main change is here
<PropertyCard
key={item?.id}
title={item?.title}
image={item?.cover_image?.url}
location={item.address}
displayFooter={false}
displayButton={false}
rating={true}
item={item}
type={item?.brand_name}
link="property">
{item?.description?.slice(0, 150)}
</PropertyCard>
))
}