React Native HTTP GET json

React Native HTTP GET json

In this section we will send HTTP GET-request in React Native application using fetch API and date.jsontest.com web-service.

React Native has an embedded fetch API that is a high-level wrapper for working with HTTP requests. It’s pretty straightforward and easy to use. Let’s look into example of getting JSON data with fetch() function.

Get JSON data from HTTP in React Native

For this example please I created a new React Native project using command:

> react-native init fetchExample

Then inside index.ios.js I implemented the code that should render the text with today’s date right when the app is loaded. To achieve this we need 2 things:

  • call the fetch() function to get JSON data from HTTP request
  • place the fetch code inside of a React lifecycle function called componentWillMount().
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class FetchExample extends Component {
  constructor() {
    super();
    this.state = {
      date: ''
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <Text>{this.state.date}</Text>
      </View>
    );
  }
  componentWillMount() {
    fetch("http://date.jsontest.com/")
      .then((response) => response.json())
      .then((responseData) => {
        console.log('a');
        this.setState({date: responseData.date});
      })
      .done();
  }
}

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

AppRegistry.registerComponent('fetchExample', () => FetchExample);

The whole magic goes inside of componentWIllMount().

The fetch function accepts a string parameter with a URL for a GET-request. You can copy-paste this URL into your browser and you will see a JSON response like this:

{
   "time": "03:30:50 PM",
   "milliseconds_since_epoch": 1467732650705,
   "date": "07-05-2016"
}

If you get an error “Network request failed“, use this post to fix the issue.

Also, note that sometimes the jsontest REST-service exceeds the quota and is not reachable.

Now run the app in the simulator and you should see it working:

react native get json

Leave a Reply

2 Comments on "React Native HTTP GET json"


Guest
Jim
9 months 27 days ago

How do you get this react native project into an Xcode project?