score:1

Your code is correct but as the guys said, the weather object will initially set to empty object {} so you just need to check it first.

const App = () => {

  const [weather, setWeather] = useState(null) // change it to null for easier check

  // useEffect() ...

  if (!weather) {
    return <div>Loading indicator</div>
  }

  return (
    <div className="App">
      <Header api={weather} />
    </div>
  )
}

Edit romantic-bartik-9oyk3

score:1

You are getting that error because you are trying to access a key that doesn't exist in the object. In the following weather is set to an empty object.

// remove this from your code
console.log('weather', weather);
// this will throw an error, since weather is an empty object.
console.log(weather.weather[0].icon);

import React, { useEffect, useState } from "react";
import axios from "axios";
import { Header } from "./Header";

export const CurrentCity = () => {
  const [weather, setWeather] = useState({});

  useEffect(() => {
    async function getData() {
      const url = `https://api.openweathermap.org/data/2.5/weather?q=Berlin&appid=${
        process.env.REACT_APP_WEATHER_KEY
      }`;
      try {
        const response = await axios.get(url);
        setWeather(response.data);
      } catch (err) {
        console.log(err);
      }
    }
    getData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return (
    <div>
      <Header api={weather} />
    </div>
  );
};

Then in your header validate your data, don't assume that you'll always get the right data.

import React from "react";

export const Header = props => {
  console.log(props);
  return (
    <div>
      {/* here validate your data */}
      <h1>{props && props.api && props.api.name}</h1>
    </div>
  );
};

You can also add a loader to show the user that you are fetching data from the server.

export const CurrentCity = () => {

  const [weather, setWeather] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [isError, setIsError] = useState(false);

  useEffect(() => {

    async function getData() {

      const url = `https://api.openweathermap.org/data/2.5/weather?q=Berlin&appid=${
        process.env.REACT_APP_WEATHER_KEY
      }`;
      try {

        const response = await axios.get(url);
        setWeather(response.data);
        setIsLoading(false);

      } catch (err) {

        setIsError(true);
        setIsLoading(false);
        console.log(err);

      }

    }
    getData();
    // eslint-disable-next-line react-hooks/exhaustive-deps

  }, []);

  return (
    <>
      {isLoading ? (
        <h1>Loading ...</h1>
      ) : isError ? (
        <p>Something went wrong</p>
      ) : (
        <Header api={weather} />
      )}
    </>
  );

};

Related Query

More Query from same tag