Answer the question
In order to leave comments, you need to log in
Is it correct to change the state asynchronously?
My code is requesting data from the API. I'm trying to change the state with react hooks and useEffect()
The problem is that it repeats the request to the server constantly without ceasing. My. API key already banned
let [weatherData, setWeatherData] = useState({})
let fetchWeatherData = async() => {
let url = `https://api.openweathermap.org/data/2.5/forecast?q=Chicago&APPID=${process.env.APIKey}&cnt=5`
let response = await fetch(url);
let data = await response.json()
await setWeatherData(data)
}
useEffect(()=>{
fetchWeatherData()
})
Answer the question
In order to leave comments, you need to log in
If you only want to run the effect once (on mount), you can pass an empty array [] as the second argument.
let [weatherData, setWeatherData] = useState({})
let fetchWeatherData = async() => {
let url = `https://api.openweathermap.org/data/2.5/forecast?q=Chicago&APPID=${process.env.APIKey}&cnt=5`
let response = await fetch(url);
let data = await response.json()
await setWeatherData(data)
}
useEffect(()=>{
fetchWeatherData()
}, [])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question