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

Is there a method in AngularJS to submit form data when the input fields are pre-populated using a GET request?

How do I submit form data in AngularJS? I have a div that populates the input field from a GET request. Now, I want to send this data using a POST method. How can I achieve this? Below is the form div: <div class="row" ng-app="myApp" ng-controller="myC ...

Tips for creating a plug-in plugin and applying the necessary parameters

(function( $ ){ var functions = { init : function( options ) { var settings = $.extend({ //Declaring default settings that can be overridden in the plugin call code: 7, listHe ...

Integrating threejs dynamically into a Create React App environment

When I am dynamically loading Three.js, the variable THREE is not found. I have created a React project using create-react-app and copied the three js file into the public folder. Here's the directory structure: src public ├── js │ └─┠...

Resolving issues with jQuery's live() method while incorporating AJAX calls

One of the challenges I'm facing is with buttons on a webpage that are part of the class "go". The code snippet below demonstrates how I handle actions related to these buttons: $(".go").live('click', this.handleAction); The issue arises w ...

"Nextjs disregarded middleware by not having it at the root of the

Within my project root, I have a middleware.js file and my nextjs version is 12.3.1 This code snippet represents my middleware.js import { NextResponse, NextRequest } from "next/server"; const PUBLIC_FILE = /\.(.*)$/ /** * * @param {Nex ...

Having trouble with the Nextjs website not properly implementing the Tailwind CSS properties

Currently I am developing a Nextjs React website. Everything looks good when I test the react app locally at localhost with tailwindcss working perfectly. However, once the website is hosted on Vercel, the text-right property stops functioning and does not ...

Using Firebase to connect and disconnect from state in React with Re-base

I'm encountering some issues with React and Firebase while using the re-base module. When attempting to retrieve content from Firebase across different components in my app, I run into a problem. On one component/"page," which is home, I have the abi ...

Modifying an item within an array of Mongoose models

I am working with a model schema that looks like this: { _id: foo cart: { items: [ { id: number name: string, } ] } } My goal is to locate the document by its id and then modify the name value of the object in ...

Sharing context sub files in Next.js can be easily accomplished by following a few simple

These are the pages on my website: /pages /gift /[slug] index.tsx /personalize index.tsx In /gift/[slug]/index.tsx, I have a component called GiftProvider that looks like this: return ( <GiftProvider gift={gift}& ...

Ways to resolve the issue of BrowserWindow not being recognized as a constructor when trying to create a child window within the Electron

Currently, I am utilizing electron to construct an application with two windows. In my attempt to open a second window from the renderer process, I have implemented the following code snippet: const electron = require('electron'); const BrowserW ...

jQuery GetJson fails to execute success function

I'm trying to use this code for an Ajax request to a JSON file: let formData = $("#myform").serialize(); $.getJSON("/files/data.json?" + formData, function(response){ alert(response); } ); However, there are no errors and the alert is n ...

Issues with displaying images in Fancybox

I've integrated FancyBox into my website, but I'm experiencing a minor issue. While the FancyBox works perfectly in Dreamweaver, it seems to malfunction in various browsers. As someone who is not well-versed in programming, I'm struggling t ...

What is causing the qtip tooltip to show up on buttons with different ids?

I have a requirement to display tooltips only for specific buttons and not for others. I am facing an issue where the tooltip intended for the TAB button is showing up when hovering over other buttons like FOO and BAR as well. Could this be due to them sha ...

Shake up your background with a random twist

Seeking assistance with customizing the Aerial template from HTML5UP. I am interested in selecting a scrolling background randomly from a pool of images. Can someone guide me on how to achieve this? Presently, the background is defined within a code block ...

What is the reason behind the blocking of Ajax GET requests without CORS, while JSONP requests are permitted?

Accessing any page on the web through a GET request using HTML tags from a different origin is possible: <script src="http://example.com/user/post?txt=sample"></script> XHR requests to other origins are blocked for security reasons. For examp ...

Modifying the color of an empty string is not feasible in Javascript

Is it possible to change the color of FirstName only when there is text input? Currently, it turns green when there's text, but I want it to turn red when it's empty. How can this be achieved? $(document).on("click", '.btn-info.mailCo ...

The function getStaticProps will return an array with no elements inside

Hey there, I'm attempting to create a Twitch clone using Next.js. I'm trying to use Next.js' getStaticProps to fetch data from the Twitch API. However, I've encountered an issue where my code is not working as expected. It returns an e ...

Concealing a block from top to bottom

I currently have a filter that is hidden when clicked, with a transition effect that moves it from the bottom to the top. I have recorded my screen to demonstrate this behavior: . However, I now need the filter to hide from top to bottom instead, essenti ...

Determine the percentage of payments, similar to Upwork, by leveraging the power

Currently, I am working on developing a percentage calculation similar to what is seen on the Upwork website. The calculation appears to be accurate when derived from the base amount at a rate of 10%. For instance, if we take a base amount of 89.00, the ...

What is the best way to showcase a value in JavaScript using CSS styling?

I'm looking to customize the background, font style, and outline for both open and closed elements in the code snippet below: a.innerHTML = "We are Open now now."; a.innerHTML = "We are Closed, arm."; Additionally, I want to appl ...