Rengkat
Rengkat

Reputation: 43

Trying to fetch data from and external API but code breaks

I'm trying to fetch data from an external API. It shows at first but when I refreshes the browser, it goes blank. The code is in my GitHub repo. thanks
https://github.com/Rengkat/weather-app.git

Upvotes: 0

Views: 212

Answers (1)

Jarmo
Jarmo

Reputation: 191

The initial state of data is {}. As a consequence, data.name and data.sys are undefined, so trying to render data.sys.country throws an error before the app can render the input field.

<div className="details">
  <div className="country">
    <h3>
      {data.name}, {data.sys.country}
    </h3>

I recommend setting the initial state of data to null and wrapping everything other than the input field in a conditional that only allows rendering if data is truthy:

function FetchDataComponent() {
  const [data, setData] = useState(null);
...
  return (
    <div className="container">
      <div className="input">
        <input
          type="text"
          placeholder="Enter country..."
          value={country}
          onChange={handleChange}
          onKeyPress={fetchData}
        />
      </div>
      {data ? (
        <div className="details">
          <div className="country">
            <h3>
              {data.name}, {data.sys.country}
            </h3>
          </div>
...

Upvotes: 0

Related Questions