Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda