Home > database >  I'd like to use async function in useEffect but it ain't work
I'd like to use async function in useEffect but it ain't work

Time:08-18

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])

CodePudding user response:

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])
  • Related