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

180
Visualizações
Data is being displayed in the console but not in screen - react js

I am able to to display the data in the console but unable to display the same in the DOM page using react . I have seen this problem but none of the answers actually work for me .Can you please tell me where I am going . Am I accessing the wrong info in SetData()

function Test() {
  const [loading, SetLoading] = useState(false);
  const [questions, SetData] = useState(null);

  const getData = async () => {
    try {
      const info = await axios.get("http://localhost:3000/info").then((res) => {
        console.log(res);
        SetData(res.data.info);
      });
      SetLoading(true);
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    getData();
  }, []);


  return <div>{loading ? questions : <ReactBootstrap.Spinner animation="border" variant="success" />}</div>;
}

export default Test;

API data format :

{
  "info": [
    {
      "question": "Angular 2 integrates easily with NativeScript, allowing you to code your native app in a . . . . . . . . . style that can run on any mobile device platform.",
      "options": ["a) declarative", "b) imperative", "c) interrogative", "d) exclamatory"],
      "answer": 0,
      "id": 0
    },
    {
      "question": "Angular 2 components can be described using ________is a way to do some meta-programming.",
      "options": [
        "a) controllers, controller",
        "b) Loaders, loader",
        "c) typescripts, typescript",
        "d) decorators, decorator"
      ],
      "answer": 3,
      "id": 1
    },
    {
      "question": "The ______ directive substitutes the normal href property and makes it easier to work with route links in Angular 2.",
      "options": ["a) RouterLink", "b) RouterRend", "c) RouterLike", "d) RouterLayer"],
      "answer": 0,
      "id": 2
    }
  ]
}

screenshot of the react page for more clarity

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

0

You are setting data into "then" function with await, so, first set the data, and after set loading in true, now your loading keep in screen.

You need set first the loading and after that set the data.

const getData = async () => {
    try {
      //First set loading in true
      SetLoading(true);
      //Then call request
      const info = await axios.get("http://localhost:3000/info").then((res) => {
        console.log(res);
        //Set data in state
        SetData(res.data.info);
        //remove loading to display the data
        SetLoading(false);
      });
      
    } catch (err) {
      console.log(err);
    }
  };
about 4 years ago · Juan Pablo Isaza Relatório

0

The response you are getting from your API call includes an array called data. You are treating res.data as an object by attempting to access res.data.info. This will return undefined and thus you are never updating your questions state. I've rewritten your code below. I hope this will work (if it doesn't, it's a step in the right direction). I have also changed it such that when getData() is called, the first thing that happens is loading is set to true, then the API call is made, then loading is set back to false.

function Test() {
  const [loading, setLoading] = useState(true);
  const [questions, setQuestions] = useState();

  const getData = async () => {
    try {
      setLoading(true)
      await axios.get("http://localhost:3000/info").then(res => {
        setQuestions(res.data);
        setLoading(false);
      });
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    getData();
  }, []);


  return <div>
    {loading ? <ReactBootstrap.Spinner animation="border" variant="success" /> : questions}
   </div>;
}

export default Test;
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