AppDividend
Latest Code Tutorials

React Native Fetch Example Tutorial From Scratch

12,564

Get real time updates directly on you device, subscribe now.

React Native Fetch Example Tutorial From Scratch is today’s leading topic. In this tutorial, we will see how to Integrating React-native apps with back-end code using fetch API. Networking is an inherently asynchronous operation. Fetch is the best Promise based networking API that was chosen for React Native. So many people confuse with the frontend and backend services. They even cannot think of how their frontend build can communicate with the server. Which is the data, that has been transferred from their application to the server? What is the datatype of the data that is moved back and forth? So in this tutorial, you will see how we can consume the backend API in our React Native build. We will use Github API for this example because it is straightforward to consume and easily understandable.

Also, you can check out the below course to learn React Native From Scratch.
React Native – The Practical Guide

React Native Fetch Example

We will start our project by installing React Native. So first, we need to install the react native project.

Step 1: Install React Native on Mac

Type the following command to install it globally; if you have already installed, then you need not install create-react-native-app globally.

sudo npm install -g create-react-native-app

After that, we need to install the actual project by the following command.

create-react-native-app Networking

create react native app example

After that, let us start the project by typing the following command.

cd Networking
npm run ios

We are going to create this small project as an iOS application. If you are a windows user, then you can not continue this example, but although you can start from the step where fetch is going to be used, so you can understand how fetch is working because it is platform independent. Now, after the compilation of the project, we will see that it will open an IOS Simulator with the following default screen.

create react native app ios example

Step 2: Make a Navigation for components.

We will use NavigatorIOS to implement the Navigation Stack. NavigatorIOS is a wrapper around UINavigationController enabling you to achieve a navigation stack. It works the same as it would on a native app using  UINavigationController, providing the same animations and behavior from UIKit.

To set up a navigator, provide the initialRoute property with a route object. The route object is used to describe each scene that your app navigates to initialRoute that represents the first route in your navigator. So you will import this component inside App.js file.

// App.js

import { StyleSheet, Text, View, NavigatorIOS } from 'react-native';

Now, after that, we need to create one component. Create one folder in the root called src and inside that create one folder called components. Inside the components folder, make one file called SearchComponent.js.

// SearchComponent.js

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

export default class SearchComponent extends Component {
  render() {
    return (
      <View style={styles.main}>
        <Text style={styles.title}>Search For Github User</Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  main: {
    flex: 1,
    padding: 30,
    marginTop: 65,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#2a8ab7'
  },
  title: {
    marginBottom: 20,
    fontSize: 25,
    textAlign: 'center'
  }
});

I have just added some styles and write the text in this component. Now, SearchComponent is the component from where we can search for the Github User and fetch his/her profile photo and display it to another component.

Okay, now import this component as an initialRoute so that, when we load our application, we can see this component as the main screen of our application.

// App.js

import React from 'react';
import { StyleSheet, Text, View, NavigatorIOS } from 'react-native';
import SearchComponent from './src/components/SearchComponent';

export default class App extends React.Component {
  render() {
    return (
        <NavigatorIOS
          style={styles.container}
          initialRoute = {{
           title: 'Fetch Example',
           component: SearchComponent
         }} />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#111111'
  },
});

So, our application screen looks like this.

IOS Fetch Tutorial

Step 3: Create Text Input for the user search.

We will use TextInput component from a react-native library. Also, I am using TouchableHighlight Component.  It is a wrapper for making views respond appropriately to touches. So, the final component with style looks like this.

// SearchComponent.js

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

export default class SearchComponent extends Component {

  render() {
    return (
      <View style={styles.main}>
        <Text style={styles.title}>Search For Github User</Text>
        <TextInput
              style={styles.searchInput}
            />
        <TouchableHighlight
                style = {styles.button}
                underlayColor= "white"
              >
              <Text
                  style={styles.buttonText}>
                  SEARCH
              </Text>
            </TouchableHighlight>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  main: {
    flex: 1,
    padding: 30,
    marginTop: 65,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#2a8ab7'
  },
  title: {
    marginBottom: 20,
    fontSize: 25,
    textAlign: 'center'
  },
  searchInput: {
    height: 50,
    padding: 4,
    marginRight: 5,
    fontSize: 23,
    borderWidth: 1,
    borderColor: 'white',
    borderRadius: 8,
    color: 'white'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor:'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  }
});

fetch library react

Step 4: Add Change and Submit events.

Okay, so what we need to do is grab the input username and pass it to the Github API. So when a user starts to type in the input field, we need to change the state of username, and then after pressing the submit button, the username is sent to the Github API to search for the user.

Related Posts
1 of 8
// SearchComponent.js

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

export default class SearchComponent extends Component {
  constructor(props) {
      super(props);
      this.state = {
        username: '',
        error: false
      }
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleChange(e) {
      this.setState({
        username: e.nativeEvent.text
      });
    }
    handleSubmit() {
      console.log(this.state.username);
    }
  render() {
    return (
      <View style={styles.main}>
        <Text style={styles.title}>Search For Github User</Text>
        <TextInput
              style={styles.searchInput}
              onChange={this.handleChange}
            />
        <TouchableHighlight
                style = {styles.button}
                underlayColor= "white"
                onPress = {this.handleSubmit}
              >
              <Text
                  style={styles.buttonText}>
                  SEARCH
              </Text>
            </TouchableHighlight>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  main: {
    flex: 1,
    padding: 30,
    marginTop: 65,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#2a8ab7'
  },
  title: {
    marginBottom: 20,
    fontSize: 25,
    textAlign: 'center'
  },
  searchInput: {
    height: 50,
    padding: 4,
    marginRight: 5,
    fontSize: 23,
    borderWidth: 1,
    borderColor: 'white',
    borderRadius: 8,
    color: 'white'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor:'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  }
});

So, when you hit the search button, then we can get the username in the console. For the console panel, you need to type the combination of these keys: cmd + d on the iOS Simulator. It will open up the new screen, and you need to Start Remote Debugging. It will open up the server URL like http://localhost:19001/debugger-ui/. Open the chrome developer tools and go to console panel. Now, type any Github Username and hit the search button. You will see that name appears on console panel because we have logged that name. Now, that username will be submitted to the Github API.

Step 5: Create FetchUser service.

Okay, so now create one folder inside src directory called services. Inside services folder, create one new file called FetchUser.js.

// FetchUser.js

export const getUserInfo = (name) => {
    let username = name.toLowerCase().trim();
    const URL = `https://api.github.com/users/${username}`;
    return fetch(URL)
            .then((res) => res.json());
}

Here, what I have done is just pass the Username from TextInput field and then change it to lower case and trimmed it for any space. Pass that username into the Github API and return the response to the calling function. Fetch library returns a promise. It is an asynchronous task and then after resolving the data, we will display it on the screen.

// SearchComponent.js

import { getUserInfo } from '../services/FetchUser';

handleSubmit() {
      getUserInfo(this.state.username)
          .then((res) => {
              if(res.message === 'Not Found') {
                this.setState({
                    error: 'User not found'
                });
              }
            else {
              this.props.navigator.push({
                title: res.name || 'No Title',
                passProps: {userInfo: res}
              });
              this.setState({
                error: false,
                username: ''
              })
            }
        });
    }

Now, create one new component inside components folder called Dashboard.js.

// DashboardComponent.js

import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image
} from 'react-native';

export default class DashboardComponent extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Image source={{uri: this.props.userInfo.avatar_url}} style={styles.image} />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    marginTop: 65,
    flex: 1
  },
  image: {
    height: 350
  }
});

Now, import this component inside SearchComponent.js file.

// SearchComponent.js

import DashboardComponent from './DashboardComponent';

handleSubmit() {
      getUserInfo(this.state.username)
          .then((res) => {
              if(res.message === 'Not Found') {
                this.setState({
                    error: 'User not found'
                });
              }
            else {
              this.props.navigator.push({
                title: res.name || 'No Title',
                passProps: {userInfo: res},
                component: DashboardComponent
              });
              this.setState({
                error: false,
                username: ''
              })
            }
        });
    }

Here, what I have done is fetch will give us a promise, and after resolving, we get the data from the server. If the user is not found, then we merely display an error, and if the user is found, then we will pass that data to the DashboardComponent.js file. It will display the user’s name and user’s image.

 

React Native Example Tutorial

Step 6: Display an error if the user is not found.

Inside render() function, we need to put the condition that if the state of the error is filled with an actual error, then we need to display the error to the user. Otherwise, we do not want to display anything.

// SearchComponent.js

render() {
    let showErr = (
      this.state.error ?
      <Text>
        {this.state.error}
      </Text> :
      <View></View>
    );
    return (
      <View style={styles.main}>
        <Text style={styles.title}>Search For Github User</Text>
        <TextInput
              style={styles.searchInput}
              onChange={this.handleChange}
            />
        <TouchableHighlight
                style = {styles.button}
                underlayColor= "white"
                onPress = {this.handleSubmit}
              >
              <Text
                  style={styles.buttonText}>
                  SEARCH
              </Text>
            </TouchableHighlight>
            {showErr}
      </View>
    )
  }

Finally, our both the SearchComponent.js and DashboardComponent.js files looks like this.

// SearchComponent.js

import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableHighlight
} from 'react-native';
import { getUserInfo } from '../services/FetchUser';
import DashboardComponent from './DashboardComponent';

export default class SearchComponent extends Component {
  constructor(props) {
      super(props);
      this.state = {
        username: '',
        error: false
      }
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleChange(e) {
      this.setState({
        username: e.nativeEvent.text
      });
    }
    handleSubmit() {
      getUserInfo(this.state.username)
          .then((res) => {
              if(res.message === 'Not Found') {
                this.setState({
                    error: 'User not found'
                });
              }
            else {
              this.props.navigator.push({
                title: res.name || 'No Title',
                passProps: {userInfo: res},
                component: DashboardComponent
              });
              this.setState({
                error: false,
                username: ''
              })
            }
        });
    }
  render() {
    let showErr = (
      this.state.error ?
      <Text>
        {this.state.error}
      </Text> :
      <View></View>
    );
    return (
      <View style={styles.main}>
        <Text style={styles.title}>Search For Github User</Text>
        <TextInput
              style={styles.searchInput}
              onChange={this.handleChange}
            />
        <TouchableHighlight
                style = {styles.button}
                underlayColor= "white"
                onPress = {this.handleSubmit}
              >
              <Text
                  style={styles.buttonText}>
                  SEARCH
              </Text>
            </TouchableHighlight>
            {showErr}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  main: {
    flex: 1,
    padding: 30,
    marginTop: 65,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#2a8ab7'
  },
  title: {
    marginBottom: 20,
    fontSize: 25,
    textAlign: 'center'
  },
  searchInput: {
    height: 50,
    padding: 4,
    marginRight: 5,
    fontSize: 23,
    borderWidth: 1,
    borderColor: 'white',
    borderRadius: 8,
    color: 'white'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor:'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  }
});

Also the DashboardComponent.js file.

// DashboardComponent.js

import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image
} from 'react-native';

export default class DashboardComponent extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Image source={{uri: this.props.userInfo.avatar_url}} style={styles.image} />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    marginTop: 65,
    flex: 1
  },
  image: {
    height: 350
  }
});

Finally, our React Native Fetch Example Tutorial From Scratch is over. Thanks for taking.

Fork Me On Github

1 Comment
  1. Ranjith says

    Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

    Check the render method of `NavigatorIOS`.

    This error is located at:
    in RCTNavItem (at NavigatorIOS.ios.js:851)
    in StaticContainer (at NavigatorIOS.ios.js:850)
    in RCTNavigator (at NavigatorIOS.ios.js:50)
    in NavigatorTransitionerIOS (at NavigatorIOS.ios.js:872)
    in StaticContainer (at NavigatorIOS.ios.js:871)
    in RCTView (at View.js:44)
    in NavigatorIOS (at App.js:8)
    in App (at renderApplication.js:34)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in AppContainer (at renderApplication.js:33)

    createFiberFromElement
    ReactNativeRenderer-dev.js:5630:10
    reconcileSingleElement
    ReactNativeRenderer-dev.js:9710:8
    reconcileChildFibers
    ReactNativeRenderer-dev.js:9794:14
    reconcileChildren
    ReactNativeRenderer-dev.js:10306:6
    updateHostComponent
    ReactNativeRenderer-dev.js:10734:4
    performUnitOfWork
    ReactNativeRenderer-dev.js:14091:21
    workLoop
    ReactNativeRenderer-dev.js:14129:41
    renderRoot
    ReactNativeRenderer-dev.js:14226:15
    performWorkOnRoot
    ReactNativeRenderer-dev.js:15193:17
    performWork
    ReactNativeRenderer-dev.js:15090:24
    performSyncWork
    ReactNativeRenderer-dev.js:15047:14
    requestWork
    ReactNativeRenderer-dev.js:14925:19
    scheduleWork
    ReactNativeRenderer-dev.js:14711:16
    enqueueSetState
    ReactNativeRenderer-dev.js:7700:17
    setState
    react.development.js:364:31

    NavigatorIOS.ios.js:682:22
    __invokeCallback
    MessageQueue.js:397:4

    MessageQueue.js:127:28
    __guard
    MessageQueue.js:297:10
    invokeCallbackAndReturnFlushedQueue
    MessageQueue.js:126:17

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.