I'm trying to learn react.
Based on what I write in the input field, the temperature should change consequently, but I can't find which is the best method to do it.
My logic tells me to put the setDegrees under the inputChange function so when I type a new city the weather also change, but I can't do it since the data i'm trying to get aren't global.
import React, {useState, useEffect} from 'react'
import axios from 'axios';
import City from './components/City';
function App() {
const [city, setCity] = useState("Rome")
const [degrees, setDegrees] = useState("")
useEffect(() => {
const options = {
url: 'https://weatherapi-com.p.rapidapi.com/current.json',
params: {q: city},
headers: {
'X-RapidAPI-Host': 'weatherapi-com.p.rapidapi.com',
'X-RapidAPI-Key': '---'
}
};
axios.request(options).then(res => {
setDegrees(res.data.current.temp_c)
}).catch( error => console.log(error))
},[])
const inputChange = e => {
setCity (e.target.value)
}
return (
<div>
<input type="text" placeholder='Type the city' onChange={inputChange}/>
<City
city = {city}
degrees = {degrees}
/>
</div>
)
}
export default App
You are missing a logic where you re-fetch results on city change, there are plenty ways to approach it, here is a simple example (lazy fetch):
function App() {
const [city, setCity] = useState("Rome");
const [degrees, setDegrees] = useState("");
const fetchDegrees = (city) => {
const options = {
url: "https://weatherapi-com.p.rapidapi.com/current.json",
params: { q: city },
headers: {
"X-RapidAPI-Host": "weatherapi-com.p.rapidapi.com",
"X-RapidAPI-Key": "---",
},
};
axios
.request(options)
.then((res) => {
setDegrees(res.data.current.temp_c);
})
.catch((error) => console.log(error));
};
useEffect(() => {
fetchDegrees();
}, []);
const inputChange = (e) => {
setCity(e.target.value);
};
return (
<div>
<input type="text" placeholder="Type the city" onChange={inputChange} />
<button onClick={() => fetchDegrees(city)}>Search city</button>
<City city={city} degrees={degrees} />
</div>
);
}