Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The data I want to get from the API returns undefined

Recently I got into React and while I was practicing I had this problem. I want to take the information from the API then see it on the console but it returns undefined. I think I made a mistake with axios but I can’t see it.

import axios from "axios";
import { useState } from "react";
import "./App.css";

function App() {
  const [place, setPlace] = useState("new york");
  const [placeInfo, setPlaceInfo] = useState({});

  const handleFetch = () => {
    const { data } = axios.get(
      `https://api.weatherapi.com/v1/forecast.json?key=931f75d818c34b51aca143737222202&q=${place}&days=1&aqi=no&alerts=no`
    );

    console.log(data);
  };

  return (
    <div className="App">
      <input
        type="text"
        value={place}
        onChange={(e) => {
          setPlace(e.target.value);
        }}
      ></input>
      <button onClick={handleFetch}>Search</button>
    </div>
  );
}

export default App;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should be using an async function and awaiting for the result, like so:

  const handleFetch = async () => {
    const { data } = await axios.get(
      `https://api.weatherapi.com/v1/forecast.json?key=931f75d818c34b51aca143737222202&q=${place}&days=1&aqi=no&alerts=no`
    );

    console.log(data);
  };

Otherwise you get a Promise as result, and since a Promise doesn’t have a data field, you are getting undefined.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading