Listing 11-20: Using useAxios
{
"coord": {
"lon": -0.1257,
"lat": 51.5085
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
],
"base": "stations",
"main": {
"temp": 285.42,
"feels_like": 284.95,
"temp_min": 284.13,
"temp_max": 286.01,
"pressure": 1008,
"humidity": 86,
"sea_level": 1008,
"grnd_level": 1005
},
"visibility": 10000,
"wind": {
"speed": 2.68,
"deg": 108,
"gust": 3.13
},
"clouds": {
"all": 75
},
"dt": 1765887608,
"sys": {
"type": 2,
"id": 2075535,
"country": "GB",
"sunrise": 1765872041,
"sunset": 1765900304
},
"timezone": 0,
"id": 2643743,
"name": "London",
"cod": 200
}import {useState,useRef} from 'react';
import useAxios from 'axios-hooks';
import {API_KEY} from './config';
function WeatherWidget() {
const [city,setCity] = useState('London');
const cityRef = useRef();
const changeCity = (e) => {
e.preventDefault();
setCity(cityRef.current.value);
}
const [{data, loading, error}, refetch] = useAxios( `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}` );
if (loading) return <p>Loading...</p>;
if (error) return <p>There was an error. {error.message}</p>;
return (
<><input type="text" ref={cityRef} /> <button onClick={changeCity}>Change City</button>
<SyntaxHighlighter language="javascript" style={github}>{JSON.stringify(data,null,2)}</SyntaxHighlighter>
</>
);
}
export default WeatherWidget;Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.
