Alex Khanenya
Alex Khanenya

Reputation: 295

How to use a variable outside the function

I have this code in React Native:

inApp1.get('isFullVersionBought').then((data) => {
    console.log(data);
    let fullversionbought = data;
});

How i can use fullversionbought variable outside this function? Thanks.

Upvotes: 0

Views: 2970

Answers (4)

Mila
Mila

Reputation: 608

The variable will be useless until it gets the data. To avoid waiting for the variable to be populated, I would recommend to use a component state. In that case, once you receive the data, you will update the state of the component:

constructor() {
  this.state = {
    fullversionbought: {}
  };

  this.getData():
}

getData() {
inApp1.get('isFullVersionBought').then((data) => {
    this.setState({
      fullversionbought: data
    });
});
}

Upvotes: 0

kamikazeOvrld
kamikazeOvrld

Reputation: 944

You have to define the variable outside of the function, not inside as it is in your code sample.

var fullversionbought;
inApp1.get('isFullVersionBought').then((data) => {
    console.log(data);
    fullversionbought = data;
});

Javascript uses lexical scope at compile time.

Upvotes: 3

RavikanthM
RavikanthM

Reputation: 598

You can not use local variables out side the function.Thats why we have instance variables.

Add an instance variable to that class and fill the data in this function

Upvotes: 0

chris g
chris g

Reputation: 1108

Define the variable "fullbersionbought" outside the function first, then assign its value from within the function.

The keyword "let", by its very definition, means scope the variable as block local. They only persist while that particular function is running.

Upvotes: 0

Related Questions