简体   繁体   中英

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> ?

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);
      });
  }
}

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));
      });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM