React Native API

API

API stands for an Application programming interface. API allows communication between two software and is also responsible for data sharing. It takes the asked data from the server and delivers it to the application.

Let us understand API with an example-

Here we can consider that API(Application programming interface) works as a mode of transferring information. suppose you went to a tea stall for having a cup of tea. so what will do? will you make tea by yourself ? or you will ask the waiter to serve tea ? obviously you will not make tea by yourself. you will be asking the waiter to serve you tea here waiter can be considered as API you just asked him to provide you tea and he went and served you tea. That's exactly what API does you just need to call it and it will provide you your asked information.

Simplified working of API :

  • API is called by the client /user by some specific action.
  • If the call is valid then API makes calls to another program/server.
  • The server gives the necessary data to API.
  • API transfers data to the user

React native Alert: It displays an alert with a particular message. The Alert () method is used to execute this process. Usually, it is a popup.

React native allows three types of alerts -

  • Simple Alert
  • Two options alert
  • Three options alert

React native geolocation API

It is used for getting location or geological location however it is slow and inaccurate. We do not need to import it. It is by default present in-app. It has different methods that are useful in web applications. Whenever we call this API, it returns the method. We will be discussing methods shortly. It is a very useful API, and as we get it by default from the react-native side, this makes it proficient because if you know about API integration, you must know how problematic it is. We often face various problems when trying to integrate an API into our app. It is also time-consuming. There are so many API available, some are paid, and some are unpaid, which will be good and provide accurate information, It is hard to identify, and some engineers charge a lot just for API integration, so having something like Geolocation API within react native is nothing less than a blessing. Let's see how to use this API by constructing an App:

App.js code:

import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity,Alert } from 'react-native';
export default class App extends Component {
    state = {
        location: null
    };




    find_Coordinates_of_mine = () => {
        navigator.geolocation.getCurrentPosition(
          locations => {
                const location = JSON.stringify(locations);
               this.setState({ location });
            },
            error => Alert.alert(error.message.has.arrived),
            { enableHighAccuracy: true, timeout: 2000, maximumAge: 2000 }
        );
    };




    render() {
        return (
            <View style={styles.container}>
                <TouchableOpacity onPress={this.findCoordinates}>
                    <Text style={styles.welcome}>Find My location :)</Text>
                    <Text>Location: {this.state.location}</Text>
                </TouchableOpacity>
            </View>
        );
    }
}




const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'pink'
    },
    welcome: {
      flex:1,
        fontSize: 25,
        textAlign: 'center',
        margin: 15
    }
}
)

Output :

React native API

 Find my location is touchable. When you click there, you will get an alert. Therefore, you will get the coordinates of your location.

Explanation:

firstly, We have imported all the components which we will need during app construction.

    state = {
        location: null
    };

we have initialize location as null to avoid wrong answers.

find_Coordinates_of_mine = () => {
        navigator.geolocation.getCurrentPosition(
          locations => {
                const location = JSON.stringify(locations);
               this.setState({ location });
            },

 This is where API is called. And the JSON file gives the user's location, but firstly it will ask whether the user gives this app permission to fetch his/her location. If the user press yes, then it will only fetch the location. after fetching, we have again initialized the location but not will null. We have given the fetched value to the location.

 error => Alert.alert(error.message.has.arrived),
            { enable high accuracy: true, timeout: 2000, maximum: 2000 }

There can be a scenario where API cannot fetch the location for some reason. Well, in that case, we need to tell the user that the error happened, so we will use an error alert to inform the user that API was unable to fetch the location this time. So the user can try again or check the API that whether everything is okay or not, then the user can move forward with the location.

<TouchableOpacity onPress={this.findCoordinates}>
                    <Text style={styles.welcome}>Find My location :)</Text>
                    <Text>Location: {this.state.location}</Text>
                </TouchableOpacity>

Here we have made a button and it is responsive as said earlier and we have given title to them using the Text component.

This is for styling purposes.

Example- 2

App.js code:

import {
  SafeAreaView,
  View,
  Text,
  StyleSheet,
  Image,
  Platform,
  Button,
} from 'react-native';
import React, {useState, useEffect} from 'react';
import Geolocation from '@react-native-community/geolocation';
 const App_mine = () => {
  const [
    currentLongitude,
    setCurrentLongitude
  ] = useState('...');
  const [
    currentLatitude,
    setCurrentLatitude
  ] = useState('...');
  const [
    locationStatus,
    setLocationStatus
  ] = useState('');
 
  useEffect(() => {
    const requestLocationPermission = async () => {
      if (Platform.OS === 'ios') {
        getOneTimeLocation();
        subscribeLocationLocation();
      } else {
        try {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            {
              title: 'Location Access Required for information',
              message: 'App needs to Access your location allow please',
            },
          );
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {




            getOneTimeLocation();
            subscribeLocationLocation();
          } else {
            setLocationStatus('Permission Denied');
          }
        } catch (err) {
          console.warn(err);
        }
      }
    };
    requestLocationPermission();
    return () => {
      Geolocation.clearWatch(watchID);
    };
  }, []);
 
  const getOneTimeLocation = () => {
    setLocationStatus('Getting Location ...');
    Geolocation.getCurrentPosition(
      (position) => {
        setLocationStatus('your location longitude and latitude are following -  ');
        const currentLongitude = 
          JSON.stringify(position.coords.longitude);
        const currentLatitude = 
          JSON.stringify(position.coords.latitude);
        setCurrentLongitude(currentLongitude);
        setCurrentLatitude(currentLatitude);
      },
      (error) => {
        setLocationStatus(error.message);
      },
      {
        enableHighAccuracy: false,
        timeout: 30000,
        maximumAge: 1000
      },
    );
  };
 const subscribeLocationLocation = () => {
    watchID = Geolocation.watchPosition(
      (position) => {
        
        setLocationStatus('Your location');
        console.log(position);    
        const currentLongitude =
          JSON.stringify(position.coords.longitude);
        const currentLatitude = 
          JSON.stringify(position.coords.latitude);
        setCurrentLongitude(currentLongitude);
        setCurrentLatitude(currentLatitude);
      },
      (error) => {
        setLocationStatus(error.message);
      },
      {
        enableHighAccuracy: false,
        maximumAge: 1000
      },
    );
  };
 
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <View style={styles.container}>
          <Text style={styles.boldText}>
            {locationStatus}
          </Text>
          <Text
            style={{
              flex:1,
             marginTop: 10,
            }}>
            Longitude: {currentLongitude}
          </Text>
          <Text
            style={{
              justifyContent: 'center',
              alignItems: 'center',
              marginTop: 26,
            }}>
            Latitude: {currentLatitude}
          </Text>
          <View style={{marginTop: 10}}>
            <Button
              title="press me "
              onPress={getOneTimeLocation}
            />
          </View>
        </View>
        <Text
          style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey'
          }}>
        </Text>
        <Text
          style={{
            fontSize: 16,
            textAlign: 'center',
            color: 'pink'
          }}>
        </Text>
      </View>
    </SafeAreaView>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'gray',
    padding: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  boldText: {
    fontSize: 20,
    color: 'pink',
    marginVertical: 26,
  },
});
 
export default App_mine;

Output:

React native API

Explanation :

import Geolocation from '@react-native-community/geolocation';

We are importing components as per our need, additionally, we are importing geolocation from the react-native community.

Next, we have used useState for basic initialization and constants.

PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            {
              title: 'Location Access Required for information',
              message: 'App needs to Access your location allow please',
            },
          );
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {

This is for permission because we know accessing any user's address without permission can be a crime.

Next, we have used lifecycle methods for the smooth working of code, and then API is called, and longitude and Lattitude are fetched in JSON format, and both of them are separated and displayed in output if it is fetched. There can be another case in which API will fail to fetch the longitude and latitude. In that case, we need to inform the user that an error is generated.

 (error) => {
        setLocationStatus(error.message);
      },
      {
        enableHighAccuracy: false,
        maximumAge: 1000
      },
    );
  };

This part is used for error handling. If API will fail to load the location then we will show errors in the place of longitude and latitude. This will help to know that we need to troubleshoot the problem otherwise we would be getting some wrong and inaccurate locations without knowing that something wrong has happened with API.

 setLocationStatus('Your location');
        console.log(position);    
        const currentLongitude =
          JSON.stringify(position.coords.longitude);
        const currentLatitude = 
          JSON.stringify(position.coords.latitude);
        setCurrentLongitude(currentLongitude);
        setCurrentLatitude(currentLatitude);

This is for initializing the longitude and latitude after the API fetches details.it gives us some broad co-ordinates and we need only longitude and latitude so we filter it using  

JSON.stringify(position.coords.longitude); and JSON.stringify(position.coords.latitude);

And then, we initialize them with respective values.

So here we have learned about the API of react-native. Both Alert and geo-locations are important to know. There are some other APIs. Too we will be learning about them in further parts. If you will understand the terminology or work and handling these APIs, then using other APIs in your app will be quite simple for you.


Related Topics

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.

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 API

API API stands for an Application programming interface. API allows communication between two software and is also responsible for data sharing. It takes the asked data from the server and delivers...

6 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.

TouchableHighlight in React Native

It is just a wrapper for making touch work properly, and it is the conventional way of handling touch gestures. Today's most future-proof solution is pressable API. pressable manages all...

2 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.

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.

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.

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.

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.

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 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 Status Bar

What is the status bar? The simplest and easiest answer to this question can be answered by looking at your mobile phone's top section. What can you see? Most probably, it's...

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.

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.

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.

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.

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.

What is a Bridge in React Native?

A React Native is generally composed of two fields or two parts: The first part is the code of JavaScript.The second one is native code. The ability to build a bridge between...

3 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.