Reputation: 85
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;
Upvotes: 1
Views: 65
Reputation: 46241
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
.
Upvotes: 2