0

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.sstatic.net/oqr7i.jpg

5
  • No image attached. And are you sure the URL you are giving is correct. Commented Mar 30, 2022 at 6:32
  • console the response and weatherData2 what you're getting Commented Mar 30, 2022 at 6:35
  • You need to add a callback in the useEffect, so that when the resonse wiill come, you can handle that and corresponding functions after call back, can be called. Commented Mar 30, 2022 at 6:36
  • on console.log(response) it is still giving the same error and with console.log(weatherdata1) it is giving empty object @AbbasHussain Commented Mar 30, 2022 at 6:45
  • ok I am trying with callback @NaveenChandraTiwari Commented Mar 30, 2022 at 6:47

1 Answer 1

2

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;  
Sign up to request clarification or add additional context in comments.

7 Comments

I have done this earlier it is working for that time but whenever I refresh my page it will give the same error again and all contents from my page gets disappear
Yes it is working fine but the point is that it is for one value suppose I have multiple values in my json and then in that case I have to do this for every value I want to implement something like once my whole API is loaded then only it will render the stuff
Thank you for your help, I still need to work on this part
I've created what you want so do you want me to add another answer?
Do you want me to add new answer or edit current one?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.