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

207
Visualizações
React API not showing the data

I am not able to retrieve content from API every time I reload my page it shows error, please see the attached image, I wanted to find the weather details using Weather API and right now I am using static latitude and longitude.

import React, { useState, useEffect } from "react";
import axios from "axios";
import { FaRegSun } from "react-icons/fa";
import "./stylesheets/stylesheets.css";

function WeatherApp1() {
  const [weatherData2, setWeatherData2] = useState({});

  const API_endpoint2 = `https://api.openweathermap.org/data/2.5/onecall?`;
  const API_key = `2a63c27d8ba0b0d14c9e5d59f39ee1ba`;

  useEffect(() => {
    async function getSecondObject() {
      const response = await axios.get(
        `${API_endpoint2}lat=28.4360704&lon=77.021184&units=metric&appid=${API_key}`
      );
      setWeatherData2(response.data);
    }
    getSecondObject();
  }, []);

  return (
    <div className="mainDiv">
      <div className="heading">
        <h1>
          <FaRegSun /> Weather
        </h1>
      </div>
      {weatherData2.current.temp}
    </div>
  );
}

export default WeatherApp1;

https://i.stack.imgur.com/oqr7i.jpg

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

0

The problem with your code is that you're trying to render {weatherData2.current.temp} before the data is returned from the weather API and that's why your weatherData2 will be undefined while rendering.

You can add a loading state for checking if the data is rendering or already rendered.

You can try below code:

import React, { useState, useEffect } from "react";
import axios from "axios";
import { FaRegSun } from "react-icons/fa";
import "./stylesheets/stylesheets.css";

function WeatherApp1() {
  const [loading, setLoading] = useState(true) // Loading state
  const [weatherData2, setWeatherData2] = useState({});

  const API_endpoint2 = `https://api.openweathermap.org/data/2.5/onecall?`;
  const API_key = `2a63c27d8ba0b0d14c9e5d59f39ee1ba`;

  useEffect(() => {
    async function getSecondObject() {
      const response = await axios.get(
        `${API_endpoint2}lat=28.4360704&lon=77.021184&units=metric&appid=${API_key}`
      );
      setWeatherData2(response.data);
      setLoading(false) // Setting the loading state to false after data is set.
    }
    getSecondObject();
  }, []);

  return (
    <div className="mainDiv">
      <div className="heading">
        <h1>
          <FaRegSun /> Weather
        </h1>
      </div>
       {/* Checking for loading state before rendering the data */}
      {loading ? (
         <p>Loading...</p>
      ) : (
         weatherData2.current.temp            
      )}
    </div>
  );
}

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