dimanche 5 avril 2020

Why does react app return undefined error?

I developed a weather app that gets the temperature from the open weather api. when the app runs it gives the following error:

Cannot read property 'main' of undefined

import React from "react";
import "./App.css";

const api = {
  key: "9a7a44b579d5edf79f70352aeef25b15",
  base: "https://api.openweathermap.org/data/2.5/",
};

class App extends React.Component {
  state = [
    {
      query: "",
      setQuery: "",
      weather: {},
      setWeather: {},
    },
  ];

  search = (evt) => {
    if (evt.key === "Enter") {
      fetch(
        `${api.base}weather?q=${this.state.query}&units=metric&APPID=${api.key}`
      )
        .then((res) => res.json())
        .then((result) => {
          this.setState({ setWeather: result });
          this.setState({ setQuery: "" });
          console.log(result);
        });
    }
  };

  dateBuilder = (d) => {
    let months = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ];
    let days = [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
    ];
    let day = days[d.getDay()];
    let date = d.getDate();
    let month = months[d.getMonth()];
    let year = d.getFullYear();

    return `${day} ${date} ${month} ${year}`;
  };
  render() {
    return (
      <div
        className={
          typeof this.state.weather.main != "undefined" `//The Error points to here`
            ? this.state.weather.main.temp > 16
              ? "app warm"
              : "app"
            : "app"
        }
      >
        <main>
          <div className="search-box">
            <input
              type="text"
              className="search-bar"
              placeholder="Search..."
              onChange={(e) => this.state.setQuery(e.target.value)}
              value={this.state.query}
              onKeyPress={this.search}
            />
          </div>
          {typeof this.state.weather.main != "undefined" ? (    `//The Error points to here`
            <React.Fragment>
              <div className="location-box">
                <div className="location">
                  {this.state.weather.name}, {this.state.weather.sys.country}
                </div>
                <div className="date">{this.dateBuilder(new Date())}</div>
              </div>
              <div className="weather-box">
                <div className="temp">
                  {Math.round(this.state.weather.main.temp)}°C 
                </div>
                <div className="weather">
                  {this.state.weather.weather[0].main}
                </div>
              </div>
            </React.Fragment>
          ) : (
            ""
          )}
        </main>
      </div>
    );
  }
}

export default App;

I used a react function with hooks. Then it worked fine. I am new to React. It would be nice if you can elaborate on the fix for this issue.




Aucun commentaire:

Enregistrer un commentaire