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?