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

224
Visualizações
React / Axios: Cannot read properties of undefined (reading '0')

I can see array with objects of data "fees" perfectly but if i wanna see a single value like fees[0]?.firstFee i get this error:

Uncaught TypeError: Cannot read properties of undefined (reading '0')

i thought ? operator would avoid this but seems like not...

const [fees, setFees] = useState();

useEffect(() => {
    const getFees = async () => {
      const res = await axios.get('/api/feesettings', {
        headers: { Authorization: token },
      });
      setFees(res.data);
    };

    getFees();
  }, []);

  console.log(fees);
  console.log(fees[0]?.firstFee );
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

The reason why you are getting an error on every render is because, you are passing no value to the state, so by default fees is undefined

const [fees, setFees] = useState();

and when you reach this line of code, you are trying to access fees[0] as if fees is an array, it is not that's why it's giving you an error Cannot read properties of undefined (reading '0')

console.log(fees[0]?.firstFee);

So change to this line of code,

const [fees, setFees] = useState([]);

if (fees.length > 1) {
    console.log(fees[0]?.firstFee);
}
about 4 years ago · Santiago Gelvez 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