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



 Elevate your app-building skills. Sign up for our newsletter today!

With this guide on login using Fetch in react native, You can easily pass the parameters to fetch api.

Imported React and Other Components

import React, {useState} from 'react';
import {
  View,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  Text,
  Alert,
} from 'react-native';

Created Required State Variables and Initialized with Values.

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

This is the function to validate email and password.

  const validate = async () => {
    if (!email) {
      Alert.alert('Please Enter Your Email id');
    } else if (!password) {
      Alert.alert('Please Enter Your Password');
    } else {
      login();
    }
  };

This is the function to fetch API.

  const login = async () => {
    try {
      let res = await fetch('http://localhost:8069/api/login', {
        method: 'POST',                                
        headers: {
          'Content-type': 'application/json',  
        },
        body: JSON.stringify({                         
          params: {
            email: email,               
            password: password,
          },
        }),
      });
      let response = res.json();
      console.log('response', response);
      if (response.result.success == true) {
        // Login Successfull.
      } else {
        // email/password not match
      }
    } catch (error) {
      setLoader(false);
      console.log(error);
    }
  };
Logging to Console.

  console.log('response', response);
Catching the Error if something messed up while Parsing the Response to JSON.

catch (error) {
         console.log(error);
    }
Logging to Console.

              console.log(error);
Body Component

     <View style={styles.container}>
      <TextInput
        style={styles.textInput}
        placeholder="Email"
        value={email}
        onChangeText={d => setEmail(d)}
      />
      <TextInput
        style={[styles.textInput, {marginVertical: 30}]}
        placeholder="Password"
        value={password}
        onChangeText={d => setPassword(d)}
      />
      <TouchableOpacity onPress={() => validate()} style={styles.loginButton}>
        <Text style={styles.loginButtonText}>Submit</Text>
      </TouchableOpacity>
    </View>
Stylesheet for Containing all the Styles

const styles = StyleSheet.create({
  container: {flex: 1, justifyContent: 'center', alignItems: 'center'},
  textInput: {
    width: 350,
    height: 50,
    padding: 5,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: 'grey',
  },
  loginButton: {
    width: 200,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
    backgroundColor: '#03339c',
  },
  loginButtonText: {color: '#ffffff', fontSize: 16, fontWeight: '500'},
});

export default App;

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.



 Check out our Other Related Blogs:










Get in touch wit​h us!

Protected by reCAPTCHA, Privacy Policy & Terms of Service apply.
Leave a Comment

Your email address will not be published.

Submit
Your comment is under review by our moderation team.