0

I have a button:

<button onClick = {() => this.test()}>test</button>

and test() function:

 test =  () => {
      var id2 = uuidv4();
      this.setState({
         id : id2,
      });
      console.log("id2 = " + id2);
      console.log("state.id =  " + this.state.id);
   }

The result I get when I click 3 times:

id2 = 122ac169-9cde-42a0-8eb4-8707eec8e1b3
state.id =  undefined
id2 = 5a7f36fd-801e-4d41-80db-677c57861fdc
state.id =  122ac169-9cde-42a0-8eb4-8707eec8e1b3
id2 = 651806cc-3893-430d-8356-c73c964213b6
state.id =  5a7f36fd-801e-4d41-80db-677c57861fdc
id2 = 61e3c613-f1c7-4dfb-a1e0-5d465f4297d5
state.id =  651806cc-3893-430d-8356-c73c964213b6

why state.id = undefined although I've set state.id = id2 already?, furthermore,at next times, state.id's values get value of previous value instead get value of id2?

dangthaii
  • 51
  • 3
  • 1
    [setState](https://reactjs.org/docs/react-component.html#setstate) > Think of setState() as a *request* rather than an *immediate command* to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. *React does not guarantee that the state changes are applied immediately.* – crashmstr Oct 04 '21 at 11:38

1 Answers1

1

setState asynchronous , hence add console log to callback

 test =  () => {
      var id2 = uuidv4();
      this.setState({
         id : id2,
      },()=>{   console.log("id2 = " + id2);
      console.log("state.id =  " + this.state.id);} );
    
   }
Ankush Verma
  • 689
  • 1
  • 8
  • 17