Home > Mobile >  Adding document in firebase firestore via react native is not working, but not throwing error
Adding document in firebase firestore via react native is not working, but not throwing error

Time:02-15

I have a react native project and am using firebase v9.

I am trying to add a user object to my user collection when a user is created via the sign up screen, but it is not adding in the database, and not throwing any errors either.

Here is my firebase.js

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseConfig = {
  apiKey: '',
  authDomain: '',
  projectId: '',
  storageBucket: '',
  messagingSenderId: '',
  appId: '',
};

let app;

if (firebase.apps.length === 0) {
  app = firebase.initializeApp(firebaseConfig);
} else {
  app = firebase.app();
}

const db = app.firestore();
const auth = firebase.auth();

export {db, auth};

I know that these connection details are correct because my firebase authentication is working correctly.

Here is my sign in screen where I attempt to add to the database.

const SignUp = ({navigation}) => {
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const createUser = async (email, password) => {
    try {
      auth
        .createUserWithEmailAndPassword(email, password)
        .then(function (user) {
          var user = auth.currentUser;
          logUser(user);
          navigation.navigate('Login');
        });
    } catch (error) {
      alert(error);
    }
  };

  async function logUser(user) {
    await addDoc(collection(db, 'users'), JSON.parse(JSON.stringify(user)));
  }

If I don't put JSON.parse/JSON.stringify, it is throwing an error saying firebase is called with invalid data, expected object, but it was a custom user object. So I know it is hitting that part of the codebase.

I have also went into my firestore 'rules' section on firebase console and changed it to requests go through for all:

      allow read, write: if true;

Thanks.

CodePudding user response:

You are using compat version of Firebase SDK but also using the new Modular SDK syntax. Try using only 1 version of the SDK as shown below:

import { db } from "..path/to/firebase/firebase.js"

async function logUser(user) {
  await db.collection("users").add(user)
}

I would recommend upgrading to Modular SDK as compat version might be removed in newer versions.

  • Related