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

121
Visualizações
React axios getting a null / undefined result

Can some go through my code and see what is the mistake I have done.
React and Axios code

import React, { useState, useEffect } from "react";
import { useParams, Outlet } from "react-router-dom";
import axios from "axios";

export default function Agent() {
    const [Agent, setAgent] = React.useState();

    const agentid = useParams();

    React.useEffect(() => {
        axios.get(`https://valorant-api.com/v1/agents/`).then((res) => {
            setAgent(res.data);
        });
    }, []);

    console.log(Agent);

    return (
        <div>
            <h1>{agentid.agentid}</h1>
        </div>
    );
}

console log result

Can someone explain why there is an undefined?

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

0

Axios already returns a data property, and with the api doing that aswell it will end up being like this:

setAgent(res.data.data);

It will display undefined at first because of the API call being asynchronous, hereby not instantly, so when the API has returned your response you're setting a state which causes the component to re-render, hence run the console.log again, and anything outside the useEffect.

about 4 years ago · Juan Pablo Isaza Relatório

0

The first undefined is expected. You are waiting for the promise to resolve when you call the API but meanwhile React continues rendering the Component. After the Promise resolves, the callback is executed, which changes the state with the data from the API. When the state changes, the whole component re-renders and you can see a second console.log with the actual data.

about 4 years ago · Juan Pablo Isaza Relatório

0

set default value to your state const [Agent, setAgent] = React.useState({}); i'm set default state as empty object. you can write as you expected mock object

use effect hook will call after component is initial render. that's why first log is undefined.

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