Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
Why doesn't this code work with an immediately invoked function?
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)
    }, [])

This says that setLoading (Right above the async function) is not a function. However, if I put the setLoading INSIDE of the async function it will work:

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

If I don't use an immediately invoked function and just make a regular function and then call it, it also works.

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

Why is the first example giving this error?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda