Riizu Riizu - 4 months ago 15
JSON Question

When Using React Native, how do you save the results of a fetch?

I am currently in the process of writing an Android React Native app powered by a JSON api served via a Ruby on Rails server. My biggest snag currently has been saving the results of a

fetch
call. My code is as follows:

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
Alert
} from 'react-native';

class MiniMinionClient extends Component {
constructor(props) {
super(props);
}

getStatus() {
return fetch('http://10.0.2.2:3000/api/v1/status.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(error);
});
}

render() {
var status = this.getStatus()
return (
<View style={styles.container}>
<Text>Version {status.version}</Text>
<Text>Last Update: {status.last_update}</Text>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});

AppRegistry.registerComponent('MiniMinionClient', () => MiniMinionClient);


I do know this is a valid endpoint, as I was able to make the same call work if I use alert posts, which I got the idea from here. I think the issue stems from the asynchronous nature of
fetch
but I am not sure how to get around this.

Any help would be much appreciated!

Answer

Here is one of the way to save and access the result of your api calls. The best way to call your api is from componentWillMount lifecycle. This lifecycle is called just before the Component is rendered.

You can either use your api call directly on componentWillMount() or call the getStatus() function you created.

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  Alert
} from 'react-native';

class MiniMinionClient extends Component {
  constructor(props) {
    super(props);
    // Initialize empty state here
    this.state = {
      version: '',
      last_update: ''
    };
  }
  componentWillMount() {
    // It's best to use your api call on componentWillMount
    this.getStatus();
  }

  getStatus() {
     fetch('http://10.0.2.2:3000/api/v1/status.json')
      .then((response) => response.json())
      .then((responseJson) => {
        // set the state of the output here
        this.setState({
          version: responseJson.version,
          last_update: responseJson.last_update
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

  render() {
    return (
      <View style={styles.container}>
      {/*You can now access the values using this.state here*/}
        <Text>Version {this.state.version}</Text>
        <Text>Last Update: {this.state.last_update}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

AppRegistry.registerComponent('MiniMinionClient', () => MiniMinionClient);