Home > Blockchain >  Api data does not rendering on page and console shows weather, wind not defined etc?
Api data does not rendering on page and console shows weather, wind not defined etc?

Time:10-30

I have been trying for hours to solve this problem but I couldn't, data is successfully displaying in the console but not rendering on the browser, I don't know why, Am I making some mistakes? I have attached my code below if anyone could solve this issue.

import React, { useState, useEffect } from "react";
import "../Componentstyle/Main.css";
export default function Maindata() {
  const [data, setData] = useState(null);

  let weather = async () => {
    const key = "1ab6ef20384db1d7d9d205d609f7eef0";
    await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=dubai&appid=${key}&units=metric&formatted=0`
    )
      .then((response) => response.json())
      .then((actualData)=> setData(actualData));

  };
  useEffect(() => {
    weather()
  }, []);
  const link = `http://openweathermap.org/img/w/${data.weather[0].icon}.png`

  return (
    <div className="maindata">
      <div className="city">{data.name}</div>
      <div className="temp">{data.main.temp} C</div>
      <div className="icon"><img src={link} alt="not found" /> </div>
      <div className="feel">feels Like {data.main.feels_like} C</div>
      <div className="wind">Wind {data.wind.speed} Km/hr</div>
      <div className="cloudy">{data.weather[0].main}</div>
      <div className="humidity">humidity {data.main.humidity}%</div>
      <div className="sunrise">sunrise :- {(new Date((data.sys.sunrise)*1000).toUTCString())} </div>
      <div className="sunset">sunset :- {new Date(data.sys.sunset*1000).toUTCString()}</div>
    </div>
  );
}

CodePudding user response:

It looks like your data starts as null so as long as your data didn't finish fetching, there is nothing inside it and it makes sense than an error will be thrown.

A simple fix would be to add a guard clause that returns some sort of a loading state. For example

if (!data) {
  return <div>Loading...</div>;
}

Your final code will look like this:

import React, { useState, useEffect } from "react";
import "../Componentstyle/Main.css";
export default function Maindata() {
  const [data, setData] = useState(null);

  let weather = async () => {
    const key = "1ab6ef20384db1d7d9d205d609f7eef0";
    await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=dubai&appid=${key}&units=metric&formatted=0`
    )
      .then((response) => response.json())
      .then((actualData)=> setData(actualData));

  };
  useEffect(() => {
    weather()
  }, []);
  
  if (!data) {
    return <div>Loading...</div>;
  }

  const link = `http://openweathermap.org/img/w/${data.weather[0].icon}.png`

  return (
    <div className="maindata">
      <div className="city">{data.name}</div>
      <div className="temp">{data.main.temp} C</div>
      <div className="icon"><img src={link} alt="not found" /> </div>
      <div className="feel">feels Like {data.main.feels_like} C</div>
      <div className="wind">Wind {data.wind.speed} Km/hr</div>
      <div className="cloudy">{data.weather[0].main}</div>
      <div className="humidity">humidity {data.main.humidity}%</div>
      <div className="sunrise">sunrise :- {(new Date((data.sys.sunrise)*1000).toUTCString())} </div>
      <div className="sunset">sunset :- {new Date(data.sys.sunset*1000).toUTCString()}</div>
    </div>
  );
}

CodePudding user response:

Try to add a loader in your code, data is not rendering on the browser because it renders the code before fetching is done try this :

import React, { useState, useEffect } from "react";
import "../Componentstyle/Main.css";
export default function Maindata() {
  const [data, setData] = useState(null);

  const [loading, setloading] = useState(true);

  let weather = async () => {
    const key = "1ab6ef20384db1d7d9d205d609f7eef0";
    await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=dubai&appid=${key}&units=metric&formatted=0`
    )
      .then((response) => response.json())
      .then((actualData) => setData(actualData));
    setloading(false);
  };
  useEffect(() => {
    weather();
  }, []);
  const link = `http://openweathermap.org/img/w/${data.weather[0].icon}.png`;

  return (
    <>
      {loading ? (
        <div className="loading">
          <h2>loading</h2>
        </div>
      ) : (
        <div className="maindata">
          <div className="city">{data.name}</div>
          <div className="temp">{data.main.temp} C</div>
          <div className="icon">
            <img src={link} alt="not found" />{" "}
          </div>
          <div className="feel">feels Like {data.main.feels_like} C</div>
          <div className="wind">Wind {data.wind.speed} Km/hr</div>
          <div className="cloudy">{data.weather[0].main}</div>
          <div className="humidity">humidity {data.main.humidity}%</div>
          <div className="sunrise">
            sunrise :- {new Date(data.sys.sunrise * 1000).toUTCString()}{" "}
          </div>
          <div className="sunset">
            sunset :- {new Date(data.sys.sunset * 1000).toUTCString()}
          </div>
        </div>
      )}
    </>
  );
}

  • Related