MadeInDreams
MadeInDreams

Reputation: 2146

How to retrieve fetch data in my native app

I would like to know how I can view data from my fetch query in my app.

I have a node that is fetched from React native and I want to display the response.

The node part;

app.get('/balance', function(req, res){
    //calling the function
    res.jsonp('0');
      console.log("CRYPTO CALLED");
      });

The react function;

_getBalanceFromApiAsync() {
 fetch('http://192.168.1.100:3000/ballance')
    .then(response => response.json())
    .then(responseJson => {
      console.log(responseJson);

      return responseJson;
    })
    .catch((error) => {
      console.error(error);
    });
}

I can see the result in the node console as well as the react console. But where it doesn't work is here.

Native app;

<Text style={styles.getStartedText}>Your Wallet Balance</Text>
          <Text> {this._getBalanceFromApiAsync()}</Text>
           </View>

The function is getting executed but I would like to display the returned value and as it is the text field remain empty

Thank you

Upvotes: 2

Views: 74

Answers (1)

Haider Ali
Haider Ali

Reputation: 1285

Its simple you need to setState for re-rendering the component. Try doing this

constructor(props){
   super(props)
this.state = {
    textData: ''
}
}

componentDidMount(){
this.getBalanceFromApiAsync()
}

getBalanceFromApiAsync() {
 fetch('http://192.168.1.100:3000/ballance')
    .then(response => response.json())
    .then(responseJson => {
      console.log(responseJson);
       this.setState({
      textData: responseJson
})
    })
    .catch((error) => {
      console.error(error);
    });
}

<Text style={styles.getStartedText}>Your Wallet Balance</Text>
          <Text> {this.state.textData}</Text>
           </View>

Upvotes: 2

Related Questions