3

This is my side project and I'd like to use an async function that returns users data. So I declared the async function outside of useEffect and try to setState in the async function.

when I console.log res in then block, it shows the result I expected but when I console.log outside of async getData function, it won't work

why setUsersData(setState) doesn't work as i expected?

const FeedPage = () => {
  const [usersData, setUsersData] = useState()

  const getData = useCallback(async () => {
    // eslint-disable-next-line promise/always-return
    await Goodlogging.inquireFeed().then((res) => {
    // when i console.log here it returns as i expected...
      console.log(res.data)
      setUsersData(res.data)
    })
  }, [])


  useEffect(() => {
    // try to console.log data but it returns undefined ...
    console.log('usersData:', usersData)
  }, [usersData])

  useEffect(() => {
    getData()
  }, [getData])

2

1 Answer 1

2

The useEffect callback can't be async, but you can declare a self-executable async function inside.

Also, side note, don't use promise syntax with async/await syntax.

 useEffect(() => {
   (async () => {
     const res = await Goodlogging.inquireFeed()
     // when i console.log here it returns as i expected...
     console.log(res.data)
     setUsersData(res.data)

   })()
 }, [getData])
Sign up to request clarification or add additional context in comments.

3 Comments

While that is correct, he OP isn't using an async callback to useEffect....
Yes, he doesn't, but this is his goal, that is what I understood from the title and description of the question, he want execute an async function inside useEffect after the component has been mounted.
Apparently it was, +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.