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