Issue in React Native and Firestore: The 'auth' property is not recognized in the specified type or an error object of unknown type

I am currently using Typescript in conjunction with Firebase and React Native.

While working on the signup screen, I included Firebase like so:

import * as firebase from 'firebase/app';
import 'firebase/auth';

In my onSignUp function, I encountered this issue:

onSignUp = async () => {
  if (this.state.email && this.state.password) {
    try {
      const response = await firebase
        .auth()
        .createUserWithEmailAndPassword(this.state.email, this.state.password);
    } catch (error) {
      if (error.code == 'auth/email-already-in-use') {
        Alert.alert('Signup Error', 'User already exists!', [
          {
            text: 'Ok',
          },
        ]);
      }
    }
  }
};

Visual Studio Code is giving me an error about auth in await firebase.auth(), stating that

Property 'auth' does not exist on type 'typeof'
.

Furthermore, it's also flagging the error.code and showing

Object is of type 'unknown'.ts(2571)
. I'm unsure of what this means and I've been stuck on it for some time now.

Here is my complete code snippet:

export interface Props {}
interface State {
  email: string;
  password: any;
  isLoading: boolean;
}

export default class LoginScreen extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);

    this.state = {
      email: '',
      password: '',
      isLoading: false,
    };
  }

  onLogin = () => {};

  onSignUp = async () => {
    if (this.state.email && this.state.password) {
      try {
        const response = await firebase
          .auth()
          .createUserWithEmailAndPassword(
            this.state.email,
            this.state.password
          );
      } catch (error) {
        if (error.code == 'auth/email-already-in-use') {
          Alert.alert('Signup Error', 'User already exists!', [
            {
              text: 'Ok',
            },
          ]);
        }
      }
    }
  };

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          placeholder="Your Email"
          keyboardType="email-address"
          autoCorrect={false}
          style={styles.txtInput}
          onChangeText={(email) => this.setState(email)}
        />
        <TextInput
          placeholder="Your Password"
          secureTextEntry
          style={styles.txtInput}
          onChangeText={(password) => this.setState(password)}
        />
        <TouchableOpacity style={styles.btnLog} onPress={this.onLogin}>
          <Text style={styles.logTxt}>Login</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

Any insights into why firebase.auth() and error.code issues are occurring? Your help would be greatly appreciated.

UPDATE: I attempted to follow the v9 guide using async/await, but it's still not functioning correctly:

import {initializeApp} from 'firebase/app';
import {firebaseConfig} from '../config/config';
import {getAuth, createUserWithEmailAndPassword} from 'firebase/auth';

export interface Props {}
interface State {
  email: string;
  password: any;
  isLoading: boolean;
}

export default class LoginScreen extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);

    this.state = {
      email: '',
      password: '',
      isLoading: false,
    };

    this.initialFirebase();
  }

  initialFirebase = () => {
    initializeApp(firebaseConfig);
  };

  auth = getAuth(this.initialFirebase);

  onLogin = () => {};

  onSignUp = async () => {
    if (this.state.email && this.state.password) {
      try {
        const response = await createUserWithEmailAndPassword(
          auth,
          this.state.email,
          this.state.password,
        );
      } catch (error) {
        if (error.code == 'auth/email-already-in-use') {
          Alert.alert('Signup Error', 'User already exists!', [
            {
              text: 'Ok',
            },
          ]);
        }
      }
    }
  };

Answer №1

If you're working with the new Modular SDK V9, you may have noticed that it uses a different syntax. If you prefer to stick with the existing syntax (v8), you can switch to the 'compat' version of imports:

import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
// import 'firebase/compat/[SERVICE]'

However, I would suggest upgrading to the new SDK as it offers certain performance benefits. You can experiment with the following syntax:

import { initializeApp } from "firebase/app"
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth"

const app = initializeApp({...config})

const auth = getAuth(app)

// in onSignUp
createUserWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    // Signed in 
    const user = userCredential.user;
    // ...
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    // ..
  });

For more information on the new SDK, you can refer to the documentation.

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

Exploring the power of Async/Await with Angular 5 HttpClient and forEach

I am struggling to implement async/await in my code to show a spinner when I click on a button and hide it once I have all the data. Below is a simplified version of what I have: .ts: isLoading: boolean = false; onLoad() { this.isLoading = true; ...

Tips for efficiently handling large Excel files in NodeJS without freezing the user interface

Currently, my NodeJS/Angular/Electron app is utilizing the ExcelJS library to read large Excel files that contain over 10,000 lines. While smaller files are processed smoothly, larger files take between 3.9 and 5 seconds to load, during which time the CSS ...

Retrieving the necessary data from my object to perform a sum calculation in angular

Having trouble retrieving an attribute from an array in my code. In my .ts file, I am fetching data from my backend endpoint like this: export class PostFeedComponent implements OnInit { data: any = {}; constructor(private http: HttpClient) { t ...

Issue with IntelliJ: TypeScript Reference Paths Are Not Relative

I am currently using IntelliJ as my IDE, but I am facing an issue with configuring gulp-typescript to compile my typescript code. The problem arises from the fact that IntelliJ does not treat my reference paths relatively, instead it references them from m ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

Using Angular's dependency injection in a project that has been transpiled with Babel

I am currently attempting to transpile my Angular 6 project, which is written in TypeScript, using the new Babel 7. However, I am facing challenges with getting dependency injection to function properly. Every time I try to launch the project in Chrome, I ...

What is the best way to ensure that the base class Resolver finishes before allowing the derived class Resolver to execute?

I have a situation where many of my resolvers (@angular/router Resolve) need to query the same data before executing their route-specific queries. To streamline this process, I want to create a resolver base class that resolves the initial data before the ...

Issue with `import type` causing parse error in TypeScript monorepo

_________ WORKSPACE CONFIGURATION _________ I manage a pnpm workspace structured as follows: workspace/ ├── apps/ ├───── nextjs-app/ ├──────── package.json ├──────── tsconfig.json ├───── ...

Angular, Transforming JSON with RxJS Operators in TypeScript

Upon receiving the JSON object (Survey) from the server, it looked like this: { "id": 870, "title": "test survey", "questions": [ { "id": 871, "data": ...

Can we limit the return type of arrow function parameters in TypeScript?

Within my typescript code, there is a function that takes in two parameters: a configuration object and a function: function executeMaybe<Input, Output> ( config: { percent: number }, fn: (i: Input) => Output ): (i: Input) => Output | &apos ...

TypeORM does not have the capability to effectively remove a row when there is a ManyToOne or

I'm currently grappling with a problem that has me stumped. I've spent countless hours trying to find a solution, but to no avail. I'm using MS-SQL on Azure. The structure of my entities is as follows: Customer and Visits: OneToMany (Prima ...

Changing icons within an ngFor loop in Angular 2

Looking for a solution: How can I toggle icons using ngFor? Situation: I am using *ngFor to iterate through an array and display category names. When a day is clicked, I want to open an accordion and show category details (which I have already managed). O ...

Using TypeScript's generic rest parameters to form a union return type

Right now, in TypeScript you can define dynamic generic parameters. function bind<U extends any[]>(...args: U); However, is it possible for a function to return a union of argument types? For example: function bind<U extends any[]>(...args: ...

Angular2/TypeScript Coding Guidelines

I am curious about the common practices and consensus among the Angular2 community when it comes to writing reusable code in TypeScript. I have gathered some information and questions related to Angular2 that I would like to discuss. Organizing Module/A ...

Best practices for organizing an array of objects in JavaScript

I have an array of objects with nested arrays inside, and I need to restructure it according to my API requirements. [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ w ...

What is the best way to access a component's data within its method using Vue and Typescript?

Starting a Vue.js project with TypeScript and using single file components instead of class-styled ones has been my goal. However, I have encountered a recurring issue where I get error TS2339 when trying to reference my components' data using the "th ...

Instead of showing the data in the variable "ionic", there is a display of "[object object]"

Here is the code snippet I'm working with: this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height( ...

Encountering the Firebase issue with error code (auth/invalid-api-key)

I keep encountering the error message 'Firebase: Error (auth/invalid-api-key) ' despite having entered all the correct authentication details. ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

What is causing certain code to be unable to iterate over values in a map in TypeScript?

Exploring various TypeScript idioms showcased in the responses to this Stack Overflow post (Iterating over Typescript Map) on Codepen. Below is my code snippet. class KeyType { style: number; constructor(style) { this.style = style; }; } fu ...