I have chosen Expo as my tool to develop an app that focuses on implementing OTP authentication

Snippet:

import React, { Component } from 'react';
    import { Text, TextInput, TouchableOpacity, View } from 'react-native';
    import auth from '@react-native-firebase/auth';
    
    export default class login extends Component {
        constructor(props) {
            super(props)
            this.state = {
                number:''
            }
        }
        signInWithPhoneNumber = async() => {
            const {number} = this.state
            const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
            console.log("confirmation ==>",confirmation)
            if (confirmation._auth._authResult) {
                this.props.navigation.navigate("Verify")
            }else {
                alert("internal error")
            }
        }
    
        render() {
            return (
                <View style={{ flex: 1 }}>
                    <View style={{ flex: 0.4, justifyContent: 'center', alignItems: 'center' }}>
                        <Text style={{ fontSize: 20 }}>Login with your number</Text>
                    </View>
    
                    <View style={{ flex: 0.4, justifyContent: 'center', alignItems: 'center' }}>
                        <TextInput
                        onChangeText = {(number) => this.setState({number:number})}
                            placeholder={"Please enter your number"}
                            style={{
                                padding: 10,
                                backgroundColor: "#fff",
                                borderBottomWidth: 1,
                                borderRadius: 10,
                                fontSize: 18,
                            }} />
                    </View>
    
                    <TouchableOpacity
                        onPress={this.signInWithPhoneNumber}
                        style={{
                            padding: 10,
                            backgroundColor: 'skyblue',
                            borderRadius: 10
                        }}><Text style={{
                            alignSelf: 'center',
                            fontWeight: 'bold',
                            paddingHorizontal: 10,
                        }}>
                            Send Code</Text>
                    </TouchableOpacity>
                </View>
            )
        }
    }
    

Error Log:

[Unhandled promise rejection: Error: You attempted to use a firebase module that's not installed on your Android project by calling f]rebase.app().
    - node_modules\@react-native-firebase\app\lib\internal\registry\nativeModule.js:227:10 in getAppModule
    ...
    [native code]:null in callFunctionReturnFlushedQueue 
    * Some other codes and explanations...

Answer №1

Ensure that the library is installed correctly and properly configured for Firebase integration. Here is a sample code snippet to guide you:

import * as React from "react";
import { Text, View, TextInput, Button, StyleSheet, TouchableOpacity, Platform } from "react-native";
import { FirebaseRecaptchaVerifierModal } from "expo-firebase-recaptcha";
import * as firebase from "firebase";

// Initialize Firebase JS SDK
// https://firebase.google.com/docs/web/setup
try {
  firebase.initializeApp({
    apiKey: 'AIzaSyApGoaZVtoVTYnftHSbT9l7nDmDVUYJYpU',
      authDomain: 'playground-d4e7b.firebaseapp.com',
      databaseURL: 'https://playground-d4e7b.firebaseio.com',
      projectId: 'playground-d4e7b',
      storageBucket: 'playground-d4e7b.appspot.com',
      messagingSenderId: '903405300293',
      appId: '1:903405300293:web:c55227a2b8064da05d112c',
  });
} catch (err) {
  // ignore app already initialized error in snack
}

export default function App() {
  const recaptchaVerifier = React.useRef(null);
  const [phoneNumber, setPhoneNumber] = React.useState();
  const [verificationId, setVerificationId] = React.useState();
  const [verificationCode, setVerificationCode] = React.useState();
  const firebaseConfig = firebase.apps.length ? firebase.app().options : undefined;
  const [message, showMessage] = React.useState((!firebaseConfig || Platform.OS === 'web')
    ? { text: "To get started, provide a valid firebase config in App.js and open this snack on an iOS or Android device."}
    : undefined);

  return (
    <View style={{ padding: 20, marginTop: 50 }}>
      <FirebaseRecaptchaVerifierModal
        ref={recaptchaVerifier}
        firebaseConfig={firebaseConfig}
      />
      <Text style={{ marginTop: 20 }}>Enter phone number</Text>
      <TextInput
        style={{ marginVertical: 10, fontSize: 17 }}
        placeholder="+1 999 999 9999"
        autoFocus
        autoCompleteType="tel"
        keyboardType="phone-pad"
        textContentType="telephoneNumber"
        onChangeText={(phoneNumber) => setPhoneNumber(phoneNumber)}
      />
      <Button
        title="Send Verification Code"
        disabled={!phoneNumber}
        onPress={async () => {
          // The FirebaseRecaptchaVerifierModal ref implements the
          // FirebaseAuthApplicationVerifier interface and can be
          // passed directly to `verifyPhoneNumber`.
          try {
            const phoneProvider = new firebase.auth.PhoneAuthProvider();
            const verificationId = await phoneProvider.verifyPhoneNumber(
              phoneNumber,
              recaptchaVerifier.current
            );
            setVerificationId(verificationId);
            showMessage({
              text: "Verification code has been sent to your phone.",
            });
          } catch (err) {
            showMessage({ text: `Error: ${err.message}`, color: "red" });
          }
        }}
      />
      <Text style={{ marginTop: 20 }}>Enter Verification code</Text>
      <TextInput
        style={{ marginVertical: 10, fontSize: 17 }}
        editable={!!verificationId}
        placeholder="123456"
        onChangeText={setVerificationCode}
      />
      <Button
        title="Confirm Verification Code"
        disabled={!verificationId}
        onPress={async () => {
          try {
            const credential = firebase.auth.PhoneAuthProvider.credential(
              verificationId,
              verificationCode
            );
            await firebase.auth().signInWithCredential(credential);
            showMessage({ text: "Phone authentication successful 👍" });
          } catch (err) {
            showMessage({ text: `Error: ${err.message}`, color: "red" });
          }
        }}
      />
      {message ? (
        <TouchableOpacity
          style={[StyleSheet.absoluteFill, { backgroundColor: 0xffffffee, justifyContent: "center" }]}
          onPress={() => showMessage(undefined)}>
          <Text style={{color: message.color || "blue", fontSize: 17, textAlign: "center", margin: 20, }}>
            {message.text}
          </Text>
        </TouchableOpacity>
      ) : undefined}
    </View>
  );
}

I followed the provided code but encountered the following error. I attempted to troubleshoot it but the issue persists:

Unable to resolve module react-native-webview from D:\React Native\SDR-Project\node_modules\expo-firebase-recaptcha\build\WebView.js: react-native-webview could not be found within the project.

If you are certain that the module exists, please try these troubleshooting steps:

  1. Clear watchman watches: watchman watch-del-all
  2. Delete node_modules and run yarn install
  3. Reset Metro's cache: yarn start --reset-cache
  4. Remove the cache: rm -rf /tmp/metro-*

Link to snake.expo.dev

Answer №2

The expo documentation also includes instructions for setting up react-native-webview

npx expo install react-native-webview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activating actions for the DOM elements that have a lower Z-index value

Is there anyone who can assist me with triggering events for DOM elements that have a lower z-index value? //HTML code ... <div> //Higher Z-index element <div id="element1" style="position: absolute;Z-index:5; height: 500px; width: 900px;">&l ...

Is there a way to move or rearrange columns in an HTML table using drag-and

I have a unique situation with my html table where I need to implement drag and drop functionality for columns instead of rows. My project is built using vue.js. While it's straightforward to drag/drop rows by setting draggable="true" on th ...

Possible scripting error hindering Bootstrap popover functionality even after initialization?

I've been attempting to integrate bootstrap popovers into the buttons on my web application, but they do not seem to appear. I have initialized the popovers in a .js script within my Django template using the following code: $('[data-toggle="po ...

What causes my button's view ID to dynamically change during runtime?

Currently, I am working on a straightforward Android application in Kotlin that focuses on changing the colors of various Views. Here is an excerpt of the code I have for setting up views and click listeners (bear in mind there are private lateinit declar ...

Utilizing JavaScript/AJAX JSON encoding for arrays: Tips for effectively utilizing the received data

I am trying to retrieve all the images from a specific folder on the server using an AJAX call. files = glob('assets/img/daily/*'); // obtain all file names $imageArr; foreach ($files as $file) { $imageArr[] = $file; } $jsonObj = json_encode ...

Creating a universally accessible handlebars helper in ExpressJS

I have a basic handlebars helper file located in helpers/handlebars.js: var hbs = require('express-handlebars'); hbs.registerHelper("inc", function(value, options) { return parseInt(value) + 1; }); Unfortunately, I am unable to utilize the ...

Exploring the functionality of JavaScript's concat method

I am trying to retrieve value1, value2, value3... but I am encountering an issue. Why am I getting this error message - "can't access property "concat", texto1 is undefined"? Please assist me! Here is the HTML code snippet: <div id=ite ...

What is the correct approach to hiding problems in Flow NPM packages to ensure that end-user applications do not encounter any errors?

When utilizing something like $FlowIssue, it cannot be ensured that it will be included in every .flowconfig file. Defining a library interface appears to only function within the specific project and not in other projects that import the package (even if ...

Can data be retrieved from a redirection page using AJAX?

I'm facing a challenge. I am attempting to complete a task that seems simple, but I am struggling with it. Let me explain the situation: I have 3 different HTML pages: The first page, named index.html, is my main page with a button that triggers a ...

Step-by-Step Guide: Unveiling a Particular Modal Post-Submission of Form with

My website has a form inside a modal, and when the form is submitted, I don't want the modal to close. However, I have encountered an issue because my SQL UPDATE statement redirects to the same page after updating the database. This disrupts the funct ...

What's the best way to propagate a browser event through a custom event?

http://jsfiddle.net/m2dqd236/ document.addEventListener('click', function (event) { $(document).trigger('click-anywhere', $.event.fix(event)); }, true); $(document).on('click-anywhere', function (event, e) { console.lo ...

What is the reason for restricting AJAX requests to the same domain?

I'm puzzled by the limitation of AJAX requests to the same domain. Can you explain the reasoning behind this restriction? I don't understand why requesting files from external locations is an issue, especially since servers making XMLHTTP reques ...

Is there a way to set a personalized callback function when closing a modal with MicroModal?

I've been utilizing MicroModal for showcasing a modal window. Everything seems to be working smoothly, except for when I try to trigger an event upon closing the modal. It's unclear to me where exactly I should implement this callback function. ...

Ways to create a looping mechanism with specified number restrictions and limitations

Can anyone assist me with this problem? I am looking to create a "looping" effect similar to the image provided. What is the logic behind this repetition? Thank you in advance for your help! Here is an example output: ...

Is it possible to send emails from a local server to Gmail, Yahoo, or Rediff?

Currently, I am developing a feature that allows users to send emails to any recipient including Yahoo and Gmail. Below is the code snippet for my contact form: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 ...

The Percentage Value for Height in CSS is Unresponsive on Android Application Interface

I am currently working on an app that displays screen content in HTML format, which is pulled from a database. To ensure compatibility with various devices, I need to use percentages for the width and height of the elements. However, I have been facing iss ...

Modify the second dropdown list using Jquery when the first dropdown list changes

I have encountered an issue with using two dropdown lists. Specifically, I am trying to implement a feature where if the user selects the option "2" in the first dropdown list, a script should be executed. Here is the script: $('select[name="servic ...

The NGX countdown timer is experiencing a discrepancy when the 'leftTime' parameter exceeds 24 hours, causing it to not count down accurately

When the leftTime configuration exceeds 864000, the timer does not start from a value greater than 24 hours. <countdown [config]="{leftTime: `864000`}"></countdown> For example: 1. When leftTime is set to `864000`, the Timer counts down from ...

What is the method for setting the content-type in an AJAX request for Android browsers?

I am facing an issue with my ajax call to the Rails server. The response from the server varies between HTML and JSON based on the content type. Surprisingly, this works smoothly on iPhone and desktop browsers like Chrome, but I am encountering a problem o ...

When using React, I noticed that adding a new product causes its attributes to change after adding another product with different attributes on the same page

Imagine you are browsing the product page for a Nike T-shirt. You select black color and size S, adding it to your cart. The cart now shows 1 Nike T-SHIRT with attributes color: black, size: S. However, if you then switch to white color and size M on the ...