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.