Estoy tratando de ordenar una lista ordenando con un valor de objeto, pero con useState
, las declaraciones if solo se activan en la declaración if pero no en if
y 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])
Esta es la lista de países:
[{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'}]
La lista es muy larga, pero esa es la lista de muestra.
MI SEGUNDO INTENTO:
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])
Esto también fracasó.
para más mira este código
Has dicho que la lista de países proviene (indirectamente) del contexto. No puede modificar directamente elementos de contexto como ese. Si desea que el componente tenga su propio orden ordenado para esa lista, tendrá que ordenarlo en cada representación (probablemente no sea lo ideal) o almacenar una versión ordenada en estado, actualizándola según sea necesario.
Algo a lo largo de estas líneas:
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