Simple React Native networking

If you are doing some cross platform mobile development, and find yourself in need of doing some simple React Native networking, never fear, fetch is here.

Here is a simple example of what one of your React Native files might look like. Keep in mind that I have gutted out a bunch of stuff from this file just to keep it readable, but you should get the idea from the networking functions getMoviesFromApiAsync() and moviesResponse() below.

import React, { Component } from 'react';
import { Platform, StyleSheet, View } from 'react-native';
import Styles from './Styles'
 
export default class Home extends Component<{}> {
 
  constructor(props) {
    super(props);
  }
 
  static navigationOptions = {
    header: (
      <View style={Styles.header}>
        <View style={{flex:1.0,justifyContent:'center',alignItems:'center'}}>
          <Text style={Styles.locBtnText}> Title </Text>
        </View>
      </View>
    )
  };
 
  render() {
    return (
      <View style={Styles.container}>
        {/* Your stuff goes here */}
      </View>
    );
  }
 
  {/* Networking call done here */}
  getMoviesFromApiAsync() {
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then(response => response.text())
      .then(text => this.moviesResponse(text))
      .catch((error) => {
        console.error(error);
      });
  }
 
  {/* Response comes in here */}
  moviesResponse(text) {
    this.setState({waitCursorShowing: false});
    console.log("Movies response: " + text);
  }
 
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor:'white',
    alignItems: 'center',
    justifyContent:'center'
  },
});

BTW, Happy Anniversary to 2001: A Space Odyssey, which debuted to the public 50 years ago today. Sure it is a little slow, but oh what a jump cut.

Leave a Reply