Home Blog Validate Login Using Fetch In React Native Example
Validate Login Using Fetch In React Native Example

Validate Login Using Fetch In React Native Example

Building any mobile application becomes more comfortable with the use of react-native. From the state of development to management, creating a full-stack app with react native requires a full codebase.

When you aim to integrate any 3rd party application with a react native mobile app, you need to authenticate the user's logged and fetch some more information. After the user is authenticated, we need to route the user to a new page.

Are you going to integrate your backend code using Fetch or have difficulty logging in using Fetch in React Native? If your answer to the above questions is yes, then you are in the right place.

React Native Framework will help you build a hierarchy of UI components used to build the Javascript code. React Native is considered to be a Mobile app development framework that will let you build native apps for both Android as well as iOS. This means while using React native in mobile application projects will help you build an app from scratch. For all your networking needs, react-native provides you with Fetch API. This will be similar to XMLHttpRequest, or you use other networking APIs before. If you want to access and manipulate the HTTPs pipeline, then Fetch API works best for you. With the use of Fetch's JavaScript interface, you can easily yield any resources asynchronously across the network.

This blog has listed some useful backend code that you can use to fetch a chunk of static content from another server. This guide on login using Fetch in react native will help you access your website directly from the URL. You can easily pass the URL to fetch and get noticeable results.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
Imported React and Other Components

import React from 'react';
import {
  StyleSheet,
  Text,
  View,
  ImageBackground,
  Image,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  Modal,
  Dimensions,
  ScrollView,
  Keyboard,
  SafeAreaView,
} from 'react-native';

Imported Constants to Use it's Variables.

import Constants from './Constants';
Exported Current App Component.

export default class Login extends React.Component {
Injected Props in to the Contructor.

constructor(props) {
    super(props);
Created Required State Variables and Initialized with Values.
this.state = {
      isLoading: true,
      dbList: [],
      selectedDb: null,
      pickerVisible: false,
      email: '',
      pwd: '',
      user: {},
    };
  }
As the Component Get Mounted. We do the Stuff Here.

componentDidMount() {
Initialized Get DbList Method to Fetch Database Lists from the Server.
   this.getDbList();
  }
This Method is for Fetching Database List from the Server.
   getDbList = () => {
    try {
Initialized Basic Fetch Method of JS.

fetch(
        
 {/* URL */}
        Constants.BASE_URL + Constants.GET_DB_LIST,
Required Variables like Method, Headers and Body

{
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: '{}',
        }
      )
Once the Fetch Completes its Operation and Generates a Response. It'll be Passed to then Method as Parameter.

.then(response => {
Parsing Response to Get JSON from the Server Response.

          response
            .json()
Once Parsing Completes its Operation and Generates a JSON. It'll be Passed to then Method as Parameter.

.then(json => {
Logging to Console.

console.log('Database List :', json);
Checking if We got any Error from the Server Side.

              if (json.error) {
Logging to Console.

console.log(json);
Alert the User if Any Error Occurs from the Server Side.

                alert(Constants.ERROR);
                return;
              }
Checking if we got the Appropriate Result from the Server Side.

if (json.result) {
Setting Database List and Preloader in the State.

                this.setState({
                  isLoading: false,
                  dbList: [...json.result],
                });
              } else {
Logging to Console.

console.log(json);
Alert the User if no Database Found in the Server.

                alert('No database exists');
              }
            })
Catching the Error if something messed up while Parsing the Response to JSON.

            .catch(error => {
Logging to Console.

              console.log(error);
Alert the User if any Error Occurred.

              alert(Constants.ERROR);
              return;
            });
        });
    } catch (error) {
Logging to Console.

      console.log(error);
Alert the User if any Error Occurs in Fetch Request.

      alert(Constants.ERROR);
      return;
    }
  };
This Method get Initialized When Clicked on Login Button. It Validates the Entered Credentials for the selected Database on the Server.

  validateAndLogin = () => {
Hide Keyboard

    Keyboard.dismiss();
Get the Required Variables from the Current State.

    let email = this.state.email;
    let pwd = this.state.pwd;
    let db = this.state.selectedDb;
A Fetch Request to Validate if the User and Email for Selected Database is Valid.

    fetch(Constants.BASE_URL + Constants.LOGIN, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        method: 'call',
        params: { login: email, password: pwd, db: db },
        id: 844267375,
      }),
    })
Once the Fetch Completes it's Operation and Generates a Response. It'll be passed to then Method as Parameter.

      .then(response => {
Parsing Response to get JSON from the Server Response.

        let json = response
          .json()
Once Parsing Completes it's Operation and Generates a JSON. It'll be passed to then Method as Parameter.

          .then(json => {
Checking if we got any Error from the Server Side.

            if (json.error) {
Logging to Console.

              console.log(json);
Alert the User if Validation is Failed.

              alert('Invalid email or password');
              return;
            }
Logging to Console.

            console.log(json);
Alert the User if Validation is Successful.

            this.setState({
              user: json.result,
            });
          })
Catching the Error if something messed up while Parsing the Response to JSON.

          .catch(error => {
            console.log(error);
Alert the User if any Error Occurs in Fetch Request.

            alert(Constants.ERROR);
            return;
          });
      });
  };
It's a Custom Body Component which Accepts any Children Component

  Body = ({ children }) => (
Image Background

<ImageBackground style={styles.Body} source={require('./images/bg.jpg')}>
      <SafeAreaView
        style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        {/* Show preloader until state variable isLoading is not false. Once it is then it'll display the children components instead. */}
        {this.state.isLoading ? (
          <View
            style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <ActivityIndicator />
          </View>
        ) : (
          children
        )}
      </SafeAreaView>
    </ImageBackground>
  );

  render() {
    return (
Custom Body Component

      <this.Body loading={this.state.isLoading}>
        {/* Logo */}
        <Image style={styles.Logo} source={require('./images/logo.png')} />
        {/* Title */}
        <Text style={styles.Title}> {'Login or Sign up'} </Text>

        {/* Select List of databse */}
        <View>
          <TouchableOpacity
            activeOpacity={Constants.ACTIVE_OPACITY}
            onPress={() => this.setState({ pickerVisible: true })}>
            <View style={styles.Select}>
              <Image
                style={styles.SelectIcon}
                source={require('./images/database-icon.png')}
                name="pwd"
              />
              <Text
                style={{
                  ...styles.SelectText,
                  color: this.state.selectedDb ? '#000000' : '#c3c3c3',
                }}>
                {this.state.selectedDb ?? 'Select Database'}
              </Text>
            </View>
          </TouchableOpacity>
          {/* Don't display Modal until any database is found on the server. */}
          {this.state.dbList.length > 0 ? (
            <Modal
              transparent={true}
              visible={this.state.pickerVisible}
              onRequestClose={() => this.setState({ pickerVisible: false })}>
              <View style={styles.SelectModal}>
                <View style={styles.SelectListWrap}>
                  <ScrollView contentContainerStyle={styles.SelectList}>
                    {/* Map database items and display a custom list */}
                    {this.state.dbList.map(item => (
                      <TouchableOpacity
                        key={item}
                        activeOpacity={Constants.ACTIVE_OPACITY}
                        onPress={() =>
                          this.setState({
                            selectedDb: item,
                            pickerVisible: false,
                          })
                        }>
                        <Text style={styles.SelectListItem}>{item}</Text>
                      </TouchableOpacity>
                    ))}
                  </ScrollView>
                  <TouchableOpacity
                    style={styles.Button}
                    onPress={() => this.setState({ pickerVisible: false })}>
                    <Text style={styles.ButtonText}>{'CANCEL'}</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </Modal>
          ) : null}
        </View>

        {/* Email / Username input field */}
        <View style={styles.Input}>
          <Image
            style={styles.InputIcon}
            source={require('./images/mail.png')}
            name="userName"
          />

          <TextInput
            style={styles.InputField}
            keyboardType={'email-address'}
            autoCorrect={false}
            autoCompleteType={'email'}
            underlineColorAndroid="transparent"
            placeholder="Enter your email / username"
            placeholderTextColor="#c3c3c3"
            autoCapitalize="none"
            onChangeText={email => this.setState({ email })}
          />
        </View>

        {/* Password input field */}
        <View style={styles.Input}>
          <Image
            style={styles.InputIcon}
            source={require('./images/pwd.png')}
            name="pwd"
          />
          <TextInput
            style={styles.InputField}
            underlineColorAndroid="transparent"
            placeholder="Enter your password"
            placeholderTextColor="#c3c3c3"
            autoCapitalize="none"
            secureTextEntry={true}
            onChangeText={pwd => this.setState({ pwd })}
          />
        </View>

        {/* Login Button */}
        <TouchableOpacity style={styles.Button} onPress={this.validateAndLogin}>
          <Text style={styles.ButtonText}>LOGIN</Text>
        </TouchableOpacity>

        {/* Forgot password and Create account option */}
        <View style={styles.Options}>
          <Text>{'Forgot Password ?  |  Create Account'}</Text>
        </View>

        {/* Social login buttons */}
        <View style={styles.SocialButtons}>
          <Image
            style={styles.SocialButton}
            source={require('./images/facebook.png')}
          />
          <Image
            style={styles.SocialButton}
            source={require('./images/gplus.png')}
          />
        </View>
        {/* Modal will visible when user logged in successfully */}
        <Modal visible={this.state.user.partner_id ? true : false}>
          <this.Body>
            {/* Logo */}
            <Image style={styles.Logo} source={require('./images/logo.png')} />
            {/* Title */}
            <Text style={styles.Title}> {'Home'} </Text>

            <Text>{'Welcome, ' + this.state.user.name}</Text>
          </this.Body>
        </Modal>
      </this.Body>
    );
  }
}
Stylesheet for Containing all the Styles

const styles = StyleSheet.create({
  Body: {
    flex: 1,
  },
  Logo: {
    height: 60,
    resizeMode: 'contain',
    marginBottom: 15,
  },
  Title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 20,
    textTransform: 'uppercase',
  },
  Select: {
    borderStyle: 'solid',
    borderColor: '#333333',
    borderWidth: 1,
    width: Dimensions.get('screen').width * 0.8,
    marginVertical: 10,
    paddingHorizontal: 10,
    flexDirection: 'row',
    alignItems: 'center',
  },
  SelectIcon: {
    width: 25,
    height: 25,
  },
  SelectText: {
    fontSize: 18,
    paddingVertical: 10,
    paddingHorizontal: 10,
    color: '#c3c3c3',
  },
  SelectModal: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  SelectListWrap: {
    height: Dimensions.get('screen').height * 0.6,
  },
  SelectList: {
    height: Dimensions.get('screen').height * 0.6 - 60,
    width: Dimensions.get('screen').width * 0.8,
    padding: 10,
    backgroundColor: '#ffffff',
  },
  SelectListItem: {
    fontSize: 18,
    paddingHorizontal: 5,
  },
  Input: {
    borderStyle: 'solid',
    borderColor: '#333333',
    borderWidth: 1,
    width: Dimensions.get('screen').width * 0.8,
    marginVertical: 10,
    flexDirection: 'row',
    paddingVertical: 10,
    paddingHorizontal: 10,
  },
  InputIcon: {
    width: 25,
    height: 25,
    marginRight: 10,
  },
  InputField: {
    fontSize: 18,
  },
  Button: {
    width: Dimensions.get('screen').width * 0.8,
    backgroundColor: '#4186c2',
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: 10,
  },
  ButtonText: {
    fontSize: 18,
    color: '#ffffff',
    paddingVertical: 10,
  },
  Options: {
    flexDirection: 'row',
    marginVertical: 10,
  },
  SocialButtons: {
    width: Dimensions.get('screen').width * 0.8,
    marginVertical: 10,
  },
  SocialButton: {
    width: '100%',
    height: 40,
    marginBottom: 10,
    resizeMode: 'contain',
  },
});

Conclusion

Networking is an asynchronous operation that needs to load resources from the remote URL. In this blog, we have discussed using a login feature using fetch in react native.

We at Kanak Infosystems have a team of Mobile Application Developers that assist you in creating various mobile applications. We frequently work to serve our clients the best software and mobile application solutions, transforming incredible apps for your business requirements.

With the use of the code mentioned in this blog, you can easily create a network of requests and handle the response without any hassle. We deliberately work hard to ensure that the code will run smoothly, and you don't handle any complications. Our team of code geeks has a hands-on backend process to be effortless for you to compile the code with your mobile applications.

The method we discussed here is straightforward to use and can be used in fetching all kinds of requests from your server. We hope that you will find all the information to login using fetch in react native platform in this blog. If you find any problem, then you can leave in our comment section. We will help you to solve all your queries as soon as possible.