Home > other >  React.js vs Javascript variable declaration
React.js vs Javascript variable declaration

Time:12-23

I have here a code using React.js, this code returns undefined in the console..

getTicket = async() =>{
    var ticketData;
    this.state.client.get('ticket').then(
        await function(data){
            ticketData = data['ticket'].toString();
            console.log(data['ticket'])
        
        }
    )
    await this.setState({ ticketInformation: ticketData })
}

while this one is javascript, this code returns the value of ticketData..

  var ticketData;
  client.get('ticket').then(
    function(data) {
      ticketData = data['ticket'];
      console.log("TICKET:: "   JSON.stringify(ticketData.id));
    }
  );

my question is, what is the difference between the 2? on the first code as you can see, I am using a async/await which should not return undefined as far as I know.. Somehow the 2nd code has no async/await but fully giving a value to the global variable.

CodePudding user response:

Try it as following, I hope you gain a goal.

   await this.state.client.get('ticket').then(
        function(data){
            ticketData = data['ticket'].toString();
            console.log(data['ticket'])
        
        }
    )

CodePudding user response:

I guess that's because when you first call getTicket function, this.state.client is undefined. You should give it a value as default first but in my knowledge, it's not good to give function to a "state". You should make the convert value function as a call back outside, not in "state" cuz React re-make the function again whenever the state value change and it wastes memory.

  • Related