My useState value of city, default London, isn't working with the fetch value URL being called in my getWeather function. It runs sometimes when I accidentally re-render the code but not any time else
import './App.css';
import Daily from './components/daily';
import {useState, useEffect} from 'react'
function App() {
const [city, setCity] = useState('London')
const [weatherData, setWeather] = useState([])
const getWeather = async() =>{
try{
const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=f8d957da06af592a1390c360ea801908&units=metric`)
const pResp = await resp.json()
setWeather(pResp)
}
catch{
console.log('error')
}
}
useEffect(()=>{
getWeather()
},[])
return(
<>
<Daily {...weatherData}></Daily>
</>
)
}
export default App;
code here
The problem was that the weatherData was being passed through before it fetched and formatted properly, to fix that I just added a loading screen and render delay so the data is always there New Code
import './cssdirect/App.css';
import Daily from './components/daily';
import {useState, useEffect} from 'react'
import Loading from './Loading';
function App() {
const [loading, setLoading] = useState(true)
const [city, setCity] = useState('paris')
const [weatherData, setWeather] = useState([])
const getWeather = async() =>{
setLoading(true)
try{
const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=f8d957da06af592a1390c360ea801908&units=imperial`)
const pResp = await resp.json()
setWeather(pResp)
setLoading(false)
}
catch{
console.log('error')
}
}
useEffect(()=>{
getWeather()
},[])
if(loading==true){
return <Loading/>
}
else{
return <Daily {...weatherData}/>
}
}
export default App;