Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
useEffect, overwrites the if statement

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda