Skip to content

Instantly share code, notes, and snippets.

@Chojiu15
Created December 14, 2021 16:22
Show Gist options
  • Save Chojiu15/7322a658c2f045c11d49f7c178e0172c to your computer and use it in GitHub Desktop.
Save Chojiu15/7322a658c2f045c11d49f7c178e0172c to your computer and use it in GitHub Desktop.
WeatherApiSearch
import "./App.css";
import { useState, useEffect } from "react";
import axios from "axios";
const App = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false)
const [querie, setQuerie] = useState('')
const [search, setSearch] = useState('')
const API_KEY = bb6d467ceb3d45cea8491338211412
const URL = `http://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=${search}&aqi=no`;
useEffect(() => {
fetchData();
}, [search]); // The querie state decide whenever we run the useEffect / everytime we change the querie value the fetchData will be called with a different value in the URL
const fetchData = () => {
axios
.get(URL)
.then((res) => {
setData(res.data)
setLoading(true)
})
.catch((err) => console.log(err));
};
const handleSubmit = (e) => {
e.preventDefault()
setSearch(querie)
setQuerie('')
}
return (
<div style={{ textAlign: "center" }}>
<form onSubmit={handleSubmit}>
<input value={querie} onChange={e => setQuerie(e.target.value)} />
<button type='submit'>
Search
</button>
</form>
{loading ? (
<div>
<h1>{data.location.name}</h1>
<h2>{data.location.country}</h2>
<p>{data.current.temp_c}</p>
<p> The humidity level is : {data.current.humidity} </p>
<img src={data.current.condition.icon} alt={data.current.condition.text} />
</div>
)
: <h1>Please search for a city</h1>
}
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment