0

I am not sure if I am mistaken about the asynchronous or React itself.

const fetchData = async () => {
        const response = await sessionApi.get("/sessions", {
            headers: {
                Authorization: user.user?.token
            }
        })

        if (response.data.success) {
            setSessionData(response.data.message)
            console.log(sessionData)
        }
    }

this is my fetchData.I try using async in function when I console.log to show data it show empty [] if I change to

console.log(response.data.message)

It shows my data from request.So that my api is not wasted.

useEffect(() => {
        fetchData()
        console.log(sessionData)
    }, [])

Ok then I use useEffect in my React web then I console.log(sessionData) but it still empty list

const [sessionData, setSessionData] = useState([])

that is my my state. Maybe I am mistaken. Please tell me where I missed.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Applesz
  • 15
  • 3
  • Does this answer your question? [console log the state after using useState doesn't return the current value](https://stackoverflow.com/questions/54867616/console-log-the-state-after-using-usestate-doesnt-return-the-current-value) – buzatto Mar 25 '21 at 15:52

5 Answers5

1

As @jon-parret said, you can't console log your state like this just after setting the state value.

If you want to do something when your sessionData is set or changed, you can do something like this.

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

useEffect(() => {
    console.log(sessionData)
}, [sessionData])
Sennen Randika
  • 1,566
  • 3
  • 14
  • 34
0

The set callback from React.useState is asynchronous, so console logging your sessionData in your API call function will not log the data received.

jon-perrett
  • 94
  • 1
  • 6
0

try having a separate useEffect that listens for the sessionData to be populated

useEffect(() => {
  if(sessionData) {
    console.log(sessionData);
  }
}, [sessionData])

the setSessionData() callback will be added to the end of the queue so will run after the console.log in your code which is already in the call stack

Rob Sutcliffe
  • 321
  • 1
  • 14
0

setSessionData is asynchronous, so the moment you set a new state, it's not guaranteed that sessionData is updated.

instead, you can check it by using an useEffect hooks:

useEffect(() => {
  console.log(sessionData)
}, [sessionData])
// add `sessionData` as a dependency so when it changes, the log will show
vuongvu
  • 811
  • 6
  • 15
0

Thanks you every, I can logging it with

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

useEffect(() => {
    console.log(sessionData)
}, [sessionData])

I understand that using async-await will wait for that line of code to run first. And then work on the next line That makes me wonder why my console.log isn't working.

Applesz
  • 15
  • 3