Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!