HTTP in React Native

Networking

HTTP in React-native:

we all are aware that react native is a javascript framework.HTTP is nothing but an API request, and you might think that what is the need for an API request? Well, many mobile phones require acquiring resources for loading a remorse URL. For this purpose, an API request is made.

As we know, react native is a javascript framework, so we can make HTTP requests like fetch() to handle network requests.

What is networking? Why is it important?

Networking is a way through which we connect two or more two devices using a wired connection or even wirelessly. The main purpose of networking is to share data efficiently and securely among different computers.

Sharing data with many computers at a single time can be a daunting task. We need networking for efficient and secure data transmission and receiving.

Let's get back to our topic -

fetch(): It is similar to XMLHTTP request. It provides a network facility to your device. Fetch is used to make an HTTP request for react-native.

Lets make one HTTP request using fetch() get method;

App.js code :

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  View,
  TouchableOpacity,
  Text,
} from 'react-native';
 
const App = () => {
  const DataUsingGet = () => {
    fetch('https://jsonplaceholder.typicode.com/comments', {
      method: 'GET',
    })
      .then((response) => response.json())
      .then((responseJson) => {
        alert(JSON.stringify(responseJson));
        console.log(responseJson);
      })
      .catch((error) => {
        alert(JSON.stringify(error));
        console.error(error);
      });
  };
 
 
 
 
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <View style={styles.container}>
          <TouchableOpacity
            style={styles.button_Style}
            onPress={DataUsingGet}>
            <Text style={styles.text_Style}>
               Data Using GET
            </Text>
          </TouchableOpacity>          
        </View>
          </View>
    </SafeAreaView>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#6699ff',
    justifyContent: 'center',
    padding: 20,
  },
  text_Style: {
    fontSize: 18,
    color: 'white',
  },
  button_Style: {
    alignItems: 'center',
    backgroundColor: '#ecb3ff',
    padding: 10,
    marginVertical: 10,
  },
});
 export default App;

Output:

HTPP in react

After clicking on 'data using get,' you can see the json data has been fetched.

Let's make one HTTP request using the fetch() post method;

App.js code :

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  View,
  TouchableOpacity,
  Text,
} from 'react-native';
 
const App = () => {
  const DataUsingPost = () => {
    var dataToSend = {title: 'foo', body: 'bar', userId: 10};
    var formBody = [];
    for (var key in dataToSend) {
      var encodedKey = encodeURIComponent(key);
      var encodedValue = encodeURIComponent(dataToSend[key]);
      formBody.push(encodedKey + '=' + encodedValue);
    }
    formBody = formBody.join('&');
    fetch('https://jsonplaceholder.typicode.com/comment', {
      method: 'POST',
      body: formBody,
    })
      .then((response) => response.json())
      .then((responseJson) => {
        alert(JSON.stringify(responseJson));
        console.log(responseJson);
      })
      .catch((error) => {
        alert(JSON.stringify(error));
        console.error(error);
      });
  };
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <View style={styles.container}>
          <TouchableOpacity
            style={styles.button_Style}
            onPress={DataUsingPost}>
            <Text style={styles.text_Style}>
             Data Using POST
            </Text>
          </TouchableOpacity>
        </View>
       
      </View>
    </SafeAreaView>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#6699ff',
    justifyContent: 'center',
    padding: 250,
  },
  text_Style: {
    fontSize: 28,
    color: 'white',
    fontWeight:'b'
  },
  button_Style: {
    alignItems: 'center',
    backgroundColor: '#ecb3ff',
    padding: 1,
    marginVertical: 1,
    alignContent: 'center',
    flex: 1
  },
});
 export default App;

Output:

HTPP in react

After clicking on 'data using get,' you can see the json data has been fetched.

Explanation of code :

As both the code above is identical the only difference is the mode of calling the first onjeis called by GET and the second one is called by POST and rest of the properties,methods and styles are taken same for better understanding.

const App = () => {
  const DataUsingGet = () => {
    fetch('https://jsonplaceholder.typicode.com/comments', {
      method: 'GET',
    })

In this part of the main app function, we used to fetch and give a URL of json data and declared our method as getting.

.catch((error) => {
        alert(JSON.stringify(error));
        console.error(error);
      });

This part is mainly for error handling.

If you havev given wrong URL the you might witness following warning in inspect section -

Failed to load resource: net::ERR_NAME_NOT_RESOLVED

<SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <View style={styles.container}>
          <TouchableOpacity
            style={styles.button_Style}
            onPress={DataUsingGet}>
            <Text style={styles.text_Style}>
               Data Using GET
            </Text>
          </TouchableOpacity>          
        </View>
          </View>
    </SafeAreaView>

 We have done a lot of work using this code pattern, so that it might seem quite familiar.

We have declared one button, and "onPress" is responsible for the response of a button after getting pressed. And we have given 'DataUsingGET'. This will call our function 'DataUsingGET' where we have used fetch, given URL, and exception handling method. So this is how it works.

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#6699ff',
    justifyContent: 'center',
    padding: 20,
  },
  text_Style: {
    fontSize: 18,
    color: 'white',
  },
  button_Style: {
    alignItems: 'center',
    backgroundColor: '#ecb3ff',
    padding: 10,
    marginVertical: 10,
  },
});

This is just the styling part for each component.


Related Topics

React Native Animations

Animation: animation is a method in which puppets, figures, drawings, etc., appear as moving creatures, making an illusion that things are moving. It is a unique way of expressing something...

6 minutes read.

React Native Alert

In this part of the tutorial, we will learn about react-native's alert API. It is compatible with both android and IOS. What is API? Answer - API stands for Application programming interface,...

4 minutes read.

TouchableOpacity in React Native

Touchable opacity is the most suited example if you want to make views respond to proper touch. If you want to control the opacity then it can be done by...

3 minutes read.

Lifecycle of React Native Components

We are familiar with the word “lifecycle”. In human life, the lifecycle has three phases - birthlifedeath In react native its component lifecycle is almost the same as the human lifecycle. The...

6 minutes read.

Basic knowledge of firebase for React Native

Firebase for react-native : Firebase is a mobile and web application development platform which is created in 2014 by google. It is a product of google which is offered to developers...

7 minutes read.

HTTP in React Native

Networking HTTP in React-native: we all are aware that react native is a javascript framework.HTTP is nothing but an API request, and you might think that what is the need for an...

4 minutes read.

How Does React Native Work

Working of React Native React Native is a framework that lets us write android and iOS mobile applications using JavaScript. It is interesting to see how easy it is to develop...

4 minutes read.

React native calender

In this article, we will be learning to add calendar features to react native app. So before creating the calendar, we do need to install a few packages or add some...

3 minutes read.

React Native Creating Components

React elements are where all React codes reside. The React elements are very similar to the regular React components, which have a unique style and offer contrast. Working with views When you...

3 minutes read.

React Native Components

React Native components are the same as ordinary react components, but they are different in terms of rendering and styling. All react code lives in react components. They are independent...

16 minutes read.

React Native Pressable

It manages all the touch inputs, and it is one of the core wrappers introduced in July 2022. The Two important features of pressable are listed below- onPressInonPressOut onpressIn: We already know the...

3 minutes read.

React Native Toast

Introduction: It is a message that will be displayed on the screen for a short span of time to interrupt the user. Primarily it is displayed by any user action....

5 minutes read.

Why to Learn React Native

The demand for smartphone applications is ever-changing. The elder ones disappear from our remembrances, and smartphones and new applications come each day. In this turbulent ecosystem, it is struggling for...

4 minutes read.

States in React Native

We can control data of components of react-native by state and props. We are familiar with props and used them multiple times previously. Props: This is used to customize components and...

3 minutes read.

Redux in React Native

 It is a really amazing library of javascript, react, and react-native. It is very popular in react native domain. Every react and react native developer must know the redux it...

7 minutes read.

Difference Between React.js and React Native

React js vs. React-native React native:  react-native is an open-source javascript framework that can be used to develop native mobile apps for IOS and android. Facebook released it in 2015 and witnessed...

3 minutes read.

React Native Sound

It is a great way to connect to the user. Just a tiny "ting" of any email received, or some sound for deleting a file or sound for sending a...

8 minutes read.

Advantages and Disadvantages of React Native

Advantages of using React Native It is observed that React Native stands out from most of the existing methods of cross-platform application development, like Ionic or Cordova, because React Native renders...

3 minutes read.

React Native indicator

React native activity indicator : React native activity indicator is one of the react-native components. We all have seen it several times. It's the loader. Look at the picture below - So now...

4 minutes read.

React Native Tutorial

Introduction to react native : React-native is an open-source javascript framework that can be used to develop native mobile apps for IOS and android. It is released by Facebook in 2015...

4 minutes read.