useEffect(() => { try { setLoading(true) (async () => { const res = await fetch('https://reqres.in/api/users') const { data } = await res.json() setData(data) })() } catch(error) { console.log(error) setError(error) } setLoading(false) }, [])Esto dice que setLoading (justo encima de la función asíncrona) no es una función. Sin embargo, si coloco setLoading DENTRO de la función asíncrona, funcionará:
useEffect(() => { try { (async () => { setLoading(true) const res = await fetch('https://reqres.in/api/users') const { data } = await res.json() setData(data) })() } catch(error) { console.log(error) setError(error) } setLoading(false) }, [])Si no uso una función invocada inmediatamente y solo hago una función regular y luego la llamo, también funciona.
useEffect(() => { try { setLoading(true) async function getUsers() { // const fallback = [] const res = await fetch('https://reqres.in/api/users') const { data } = await res.json() setData(data) } getUsers() } catch(error) { console.log(error) setError(error) } setLoading(false) }, [])¿Por qué el primer ejemplo da este error?