L
L
Luke LikeSkywalker2020-01-28 05:33:11
JavaScript
Luke LikeSkywalker, 2020-01-28 05:33:11

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

1 answer(s)
D
dpws, 2020-01-28
@oolooq

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()
    }, [])

Documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question