I'm trying to sort a list by ordering with an object value, but with useState, the if statements only triggers in if statement but not both if and else :
const { countryList } = useCustomerData();
useEffect(()=>{
if(type === 'nationality'){
countryList.sort((a: CountryObject, b: CountryObject) =>
a.nationality.localeCompare(b.nationality))
}else {
countryList.sort((a: CountryObject, b: CountryObject) =>
a.country.localeCompare(b.country))
}
}, [countryList, type])
This is countryList :
[{country: 'Afghanistan', code: 'AF', prefix: '93', nationality: 'Afghan'}
1: {country: 'Ägypten', code: 'EG', prefix: '20', nationality: 'Egyptian'}
2: {country: 'Åland-Inseln', code: 'AX', prefix: '+358-18', nationality: 'Åland-Inseln'}
3: {country: 'Albanien', code: 'AL', prefix: '355', nationality: 'Albanisch'}
4: {country: 'Algerien', code: 'DZ', prefix: '213', nationality: 'Algerian'}]
The list is very long but that's the sample list.
MY SECOND ATTEMPT :
const [countryFinal, setCountryFinal] = useState<CountryType[]>([])
const value = useMemo(() => _get(values, name), [values, name]);
useEffect(()=>{
if(type === 'nationality'){
setCountryFinal(countryList.sort((a: CountryObject, b: CountryObject) =>
a.nationality.localeCompare(b.nationality)))
}else {
setCountryFinal(countryList.sort((a: CountryObject, b: CountryObject) =>
a.country.localeCompare(b.country)))
}
}, [countryList, type, setCountryFinal])
This also failed.
for more check out this code
You've said the country list comes (indirectly) from context. You can't directly modify context items like that. If you want the component to have its own sorted order for that list, you'll have to sort it on each render (probably not ideal) or store a sorted version in state, updating it as necessary.
Something along these lines:
const { countryList } = useCustomerData();
const [ sortedCountryList, setSortedCountryList ] = useState<CountryObject[]>([]); // (Or you could init it with `countryList`)
useEffect(()=>{
if (type === "nationality"){
setSortedCountryList(countryList.slice().sort((a: CountryObject, b: CountryObject) =>
a.nationality.localeCompare(b.nationality)
));
} else {
setSortedCountryList(countryList.slice().sort((a: CountryObject, b: CountryObject) =>
a.country.localeCompare(b.country)
));
}
}, [countryList, type]); // <=== Update the sorted list when either the context
// value or the sort type changes
// ...use `sortedCountryList` for rendering