I'm experiencing a problem when trying to add a document to Firebase Firestore using React Native - it doesn't seem to

I'm currently working on a React Native project that utilizes Firebase v9.

My goal is to add a user object to my user collection whenever a new user signs up through the sign-up screen. However, I've encountered an issue where the user object is not being added to the database, and there are no errors being thrown.

Below is my firebase.js setup:

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 can confirm that the connection details are accurate as my firebase authentication is functioning correctly.

Next, here is a snippet of my sign-in screen where I attempt to insert data into 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)));
  }

When attempting to use the addDoc method without JSON parsing, it results in an error stating that Firebase was called with invalid data. This confirms that this portion of the codebase is being executed.

Additionally, I have adjusted the firestore rules section on the Firebase console to allow all requests to pass through:

allow read, write: if true;

Thank you for your assistance.

Answer №1

You have adopted the compat version of Firebase SDK while also incorporating the new Modular SDK syntax. It is advisable to stick with just one version of the SDK, as illustrated below:

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

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

I suggest considering transitioning to the Modular SDK since the compat version could be phased out in future releases.

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

Utilizing data attributes to configure jQuery plugin settings

Having trouble assigning options to an array value in a jQuery plugin using data attributes. When referencing the data attribute with a class selector: $('.tm-input').tagsManager( { prefilled: $('.tm-input').data('loa ...

Having difficulty viewing the images clearly

My JavaScript codes for scrolling images are not displaying all the images when viewed on Google Chrome. Is there a solution available? Below is the included JS code and CSS. data=[ [" images/img1.jpg"," Image1","pic01.jpg"], [" images/img2.jpg","Image2 " ...

The Ionic framework is showing an error that says "'LoginCtrl' is not defined as a function."

I encountered an issue while attempting to set up simple navigation in my ionic application. The error message I received was: "Argument 'LoginCtrl' is not a function, got undefined in the Ionic. What could be causing this problem?" Here is a sn ...

The JSON request was unsuccessful in sending the JSON object to PHP, resulting in an empty var_dump

I am encountering an issue where my $_POST array in PHP is empty when I try to pass a JSON object with an AJAX request on my JavaScript page. Here is the JavaScript code: function send(cat, subcat) { var type = cat.options[cat.selectedIndex].text ...

Increment the text counter following the uploading of an image file with html format

I have a form in which I am checking the character limit that a user can input into a text field using the 'onkeyup' attribute to update it in real time. Now, I want to achieve a similar function for image uploading. When a user selects an image ...

Can TypeScript automatically deduce keys from a changing object structure?

My goal here is to implement intellisense/autocomplete for an object created from an array, similar to an Action Creator for Redux. The array consists of strings (string[]) that can be transformed into an object with a specific shape { [string]: string }. ...

Having trouble with JSONP cross-domain AJAX requests?

Despite reviewing numerous cross-domain ajax questions, I am still struggling to pinpoint the issue with my JSONP request. My goal is simple - to retrieve the contents of an external page cross domain using JSONP. However, Firefox continues to display the ...

Convert data in JavaScript and send it as a string in PHP

I'm currently facing a small issue with my JavaScript code. Specifically, I am using AJAX and attempting to retrieve a variable in PHP. Everything seems to be working fine except for the "param" data. Below is the snippet of my code: $('#sign ...

The local variable within the Angular constructor is not initialized until the ngOnInit() function is invoked

I am encountering difficulties with making backend calls from Angular. In my component, I am fetching the "category" parameter from the URL as shown below: export class ProductsComponent{ productList = [] category = "" $params; $products ...

I need to obtain the URL pathname on a server component in Next.js version 13 - how is this achieved

I'm facing an issue with retrieving the pathname of a server component located in the app directory. Despite attempting to obtain it through window.location, I haven't been successful. Is there an alternative method I can use to achieve this? ...

Tips for clearing Nightwatch session storage efficiently

To ensure the pop-up functionality was working properly, I had to reset the browser's session storage. By doing this, the pop-up will reappear. Is there a way to clear the page's Session Storage in Nightwatch? ...

Pass the ID of a dynamic textbox element to a child window upon clicking a link

One of the challenges I'm facing involves a textbox labeled "Branch Code" that links a branch to a corporate card transaction. At times, there is a requirement to split a transaction among multiple branches. To facilitate this process, I am constructi ...

Obtaining the calculated background style on Firefox

Back when my userscript was only functional on Chrome, I had a setup where I could copy the entire background (which could be anything from an image to a color) from one element to another. This is how it looked: $(target).css('background', $(so ...

A guide on updating data with duplicate values in Knex

Suppose I have the following array of data: const customerIds = [ '7d8206d2-74bc-4b90-a237-37f92486cde4', 'e594fe7f-d529-4a2f-ab24-ffc4e102268c', '7d8206d2-74bc-4b90-a237-37f92486cde4' ] As seen, there are duplicate IDs ...

Tips for sending multiple pieces of data to an Arduino with NodeJS's serialport library

I am having trouble writing multiple data using the same port, but I see that node-serialport allows for reading multiple data functions simultaneously. How can I also write multiple data at the same time? This is how I have attempted it: - index.js- con ...

Learn to save Canvas graphics as an image file with the powerful combination of fabric.js and React

I am currently utilizing fabric.js in a React application. I encountered an issue while attempting to export the entire canvas as an image, outlined below: The canvas resets after clicking the export button. When zoomed or panned, I am unable to export co ...

Switch between Fixed and Relative positions as you scroll

Just a small adjustment is needed to get it working... I need to toggle between fixed and relative positioning. JSFiddle Link $(window).on('scroll', function() { ($(window).scrollTop() > 50) ? ($('.me').addClass('fix ...

Navigating views with ReactJS using ES5

I have been searching for ReactJs guides, but most of them are based in ES5. As a result, I have begun using ReactJS in this manner. Now that I understand how to create all my components, I am ready to build a small single-page-application. However, I am s ...

The loss of Webgl context that remains unrecovered

I am facing an issue with the loss and restoration of webgl context. My application is quite complex, containing a lot of data, graphs, lists, and maps. Within the map section, I utilize webGL to ensure optimal performance. My code effectively manages th ...

What is the best way to use jQuery to emphasize specific choices within an HTML select element?

Seeking help with jQuery and RegEx in JavaScript for selecting specific options in an HTML select list. var ddl = $($get('<%= someddl.ClientID %>')); Is there a way to utilize the .each() function for this task? For Instance: <select i ...