No data is being recorded in the Firestore database

This component in nextjs is designed to write data to a firestore database after the user clicks a button. Unfortunately, Firebase seems to be having trouble writing the data, even though the alert message following the supposed data dump is successful. I have checked my process.env file to rule out any potential issues there.

Here's the code snippet for writing to the cloud firestore:

import firebase from 'firebase/app'
import 'firebase/firestore'

const WriteToCloudFirestore = () => {

    const sendData = () => {
        try {
            //send data
            firebase
                .firestore()
                .collection('myCollection')
                .doc('my_document')
                .set({
                    string_data: 'string',
                    more_data: 123
                })
                .then(alert('data sent to firestore'))
        }
        catch(e) {
            console.log(e)
            alert(e)

        }
    }

    return (
        <>
            <button onClick={sendData}>send data to cloud firestore</button>
        </>
    )
}

export default WriteToCloudFirestore

If you need additional files, let me know. Firebase initialization has been confirmed on my app. After browsing through similar questions on this forum, I came across an issue related to null data return, but I believe that's not relevant here as I am adding data to my Firestore set method.

Answer №1

When it comes to Javascript alerts, they function synchronously, meaning they pause any code execution until the alert is acknowledged. Once you dismiss the alert, your data will be sent to Firestore. Therefore, it's important to handle the promise returned by Firestore's set method before displaying the alert.

firebase
      .firestore()
      .collection("myCollection")
      .doc("my_document")
      .set({
        string_data: "string",
        more_data: 123,
      })
      .then(() => {
        console.log("Data added")
        alert("Data sent to Firestore")
      })
      .catch((e) => console.log(e));

Alternatively, you can utilize the async-await syntax:

const sendData = async () => {
    console.log("Sending Data");
    try {
      await firestore.collection("myCollection").doc("my_document").set({
        string_data: "string",
        more_data: 123,
      })
      alert("Data successfully added to Firestore")
    } catch (e) {
      console.log(e)
    }
}

To learn more about this behavior, check out this informative blog post.

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

What is the reason behind arr.reverse() flipping the original array?

My goal is to reverse an array and store the reversed version in a new array without altering the original array. Here is the code I am using: var arr= ["1", "2", "5"] var arrTwo = arr.reverse(); console.log(arrTwo) \\ ["5" , "2" , "1"] console. ...

The fetch() POST request is met with an error message stating "415 Unsupported Media Type"

I keep encountering a 415 error when attempting to upload a PDF file using fetch(). The PDF file resides in the same directory as the js file, and the name is correct. async function uploadFile(filePath, extension, timestamp) { const url = "https ...

I initially had ngRoute set up in my app, but decided to make the switch to ui-router. However, now it seems like

I currently have an application set up using express and angular. I decided to transition to ui-router in order to utilize multiple views, but it doesn't appear to be functioning as expected. app.js app.use(express.static(path.join(__dirname, ' ...

JavaScript event triggered when an element is displayed on the page using AJAX

Is it feasible in JavaScript to initiate a function when an element, like a div, becomes visible on the screen? I am working on an infinite grid that expands in both directions, and I want to fetch elements dynamically through AJAX as the user scrolls. A ...

Error: Axios return value is undefined if user is not found by the function

Trying to retrieve error messages from Express server using Redux Toolkit has presented some challenges. When no user is found, an error message is sent with a status code. Postman works fine in getting the error response but encountering issues on the cli ...

Issue with Framer Motion Modal: Animation presence fails to function

Currently, I am facing an issue with the exit animation of a modal created using framer motion. While the initial animation on opening the modal works perfectly fine, the exit animation fails to trigger and the modal disappears abruptly without any transit ...

Utilize AJAX within an Angular method

I am encountering 2 issues with the $http function in this particular code snippet. $scope.buttonClick = function(){ // Sending input data $.post('lib/add_contact.php', $scope.contact, function(data){ data = angular.fromJ ...

The Jquery click event refuses to trigger

Below is the JavaScript code that is not functioning: $('#change-priority-modal').find('.btn-primary').unbind().on("click", function () { //my_func_body } Interestingly, the code works perfectly fine in the developer console. I would ...

How to Capture Clicks on Any DOM Element in React

Currently working on a web project using React and Node. My goal is to monitor all clicks across the entire document and verify if the previous click occurred within a 2-minute timeframe. ...

Which is the best choice: MySQL stored procedures or PHP code?

When faced with a general dilemma, is it commonly favored to utilize MySQL stored procedures as opposed to creating a PHP script that accomplishes the same calculations and queries? What advantages does each approach offer? ...

Creating a full-width tab card with Bootstrap-Vue: A step-by-step guide

I stumbled upon something similar in the documentation for bootstrap-vue: A card with tabs: Now, how can I style the tabs to look like this: This is my current code: <b-card no-body> <b-tabs card> <b-tab title="Tab 1" active& ...

jQuery toggle functioning in one scenario, but failing in another

My experience with JS/Jquery is limited which might explain why I'm struggling with this. I am attempting to hide some text on a page and then make it visible again by clicking on a toggle link. The JavaScript code below is what I have been using. The ...

Sending a JavaScript value to PHP after a quiz has been completed

I've created a web page where users can take quizzes. These quizzes dynamically generate questions using JavaScript each time they are accessed. Disclaimer: I'm fairly new to JavaScript. Once the user completes the quiz, they receive their fina ...

Is there a more efficient method for iterating through this object?

Working with JSON and JS var data = { "countries": { "europe" : [{name: "England", abbr: "en"}, {name: "Spain", abbr: "es"}], "americas" : [{name: "United States"}], "asia" : [{name: "China"}] } }; JavaScript Loop for (k in data) { fo ...

Encountering a Basic React Issue: Unable to Implement @material-ui/picker in Next.js

I'm currently attempting to integrate the @material-ui/pickers library into my Next.js application. In order to incorporate the Picker provider, I followed the guidance provided in the Next.js documentation by adding the _app.js file inside /pages: i ...

Having trouble loading AngularJS 2 router

I'm encountering an issue with my Angular 2 project. Directory : - project - dev - api - res - config - script - js - components - blog.components.js ...

Filtering data based on the model in React Native allows you to refine and organize

This code snippet represents a modal that contains two custom dropdown components, a text input, and a button. When the button is clicked, it filters data from an API. Currently, I am struggling to create a functional filter function despite multiple atte ...

Limit an object to only contain interface properties

Suppose we have the following object: o {a : 1, b : 2} and this interface defined as: interface MyInterface { a : number } We are now looking to create a new object that represents the "intersection" of o and the MyInterface: o2 : {a : 1} The mai ...

The browser displays the jQuery ajax response instead of passing it to the designated callback function

I have a web application that connects to another web service and completes certain tasks for users. Using codeigniter and jQuery, I have organized a controller in codeigniter dedicated to managing ajax requests. The controller executes necessary actions ...

Rearranging div placement based on the width of the screen

I am currently working on building a responsive website and I need two divs to switch positions depending on the screen width, both on initial load and when resizing. Despite my efforts in researching and trying various options, I have not been successful ...