jorganinho
jorganinho

Reputation: 49

How to get data from fetch inside a function in React Native

I am trying to fetch data from external api and show that on display. When I press button it calls function which console things normally but can't show returned value.

export default function HomeScreen() {  
  return (
    <View style={styles.container}>
      <Button title='show data' onPress={loadText}/>
      <Text>{loadText}</Text>
    </View>
  );
  function loadText(){
    fetch('http://192.168.88.253:5000/read')
      .then((response) => response.json())
      .then((responseJson) => {
        return (
          console.log(responseJson.city)
        );
      })
      .catch((error) => {
        console.error(error);
      });
  }
}

If I understand it, loadText function must return responseJson.city value as a string. How can I show it in <View> or <Text>?

Upvotes: 1

Views: 2510

Answers (2)

Pradeep
Pradeep

Reputation: 59

you can use alert() to display the data.

alert is the popup which will be displayed on the mobile screen.

export default function HomeScreen() {  
  return (
    <View style={styles.container}>
      <Button title='show data' onPress={loadText}/>
      <Text>{loadText}</Text>
    </View>
  );
  function loadText(){
    fetch('http://192.168.88.253:5000/read')
      .then((response) => response.json())
      .then((responseJson) => {
        return (
          alert(JSON.stringfy(responseJson.city))
        );
      })
      .catch((error) => {
        alert(JSON.stringfy(error));
      });
  }
}

Upvotes: 0

Shing Ho Tan
Shing Ho Tan

Reputation: 951

export default function HomeScreen() {  
  constructor(props){
    super(props);
    this.state = {
      city: ''
    }
  }
  return (
    <View style={styles.container}>
      <Button title='show data' onPress={() => this.loadText()}/>
      <Text>{this.state.city}</Text>
    </View>
  );
 loadText(){
    fetch('http://192.168.88.253:5000/read')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({city: responseJson.city});
      })
      .catch((error) => {
        console.error(error);
      });
  }
}

Upvotes: 2

Related Questions