0

Can anyone tell me what am I doing wrong here? From the console.log, I can see the date function is working correctly. However, even after this.setState, the timestamp isn't updated. Thanks in advance!

enter image description here

enter image description here

enter image description here

Han
  • 407
  • 2
  • 5
  • 16
  • setState is asynchronous function. is the value not updated in the render function as well? If so can you provide a more complete example? – Tom Slutsky Apr 18 '20 at 11:49
  • @TomSlutsky I see! I didn't know setState is an asynchronous function. I'll resolve this with async-await then! Thanks! – Han Apr 18 '20 at 12:08

1 Answers1

0

You need to use setState with callback

According to official docs

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

this.setState((prevState)=>{
   userInfo:{
       ...prevState.userInfo,
       timestamp:timestamp
},()=>console.log(this.state.userInfo.timestamp)) // console.log here as setState is async operation
Sarthak Aggarwal
  • 2,284
  • 1
  • 8
  • 12
  • I see! I didn't know setState is an asynchronous function. I'll resolve this with async-await! Thanks alot! – Han Apr 18 '20 at 12:09