The Firestore addDoc function seems to be malfunctioning and failing to save data to

I'm currently facing an issue while trying to save data to my Firestore database. Despite following the Firebase documentation, I am unable to see any data being written to the database.

Although there are no console errors showing up, only a simple console.log('createPlaylist') statement is visible. Moreover, the initialization of Firebase seems to be working fine as the Firestore object is displayed correctly in the console!

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_apiKey,
  authDomain: process.env.NEXT_PUBLIC_authDomain,
  projectId: process.env.NEXT_PUBLIC_projectId,
  storageBucket: process.env.NEXT_PUBLIC_storageBucket,
  messagingSenderId: process.env.NEXT_PUBLIC_messagingSenderId,
  appId: process.env.NEXT_PUBLIC_appId,
  measurementId: process.env.NEXT_PUBLIC_measurementId,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Cloud Firestore and obtain a reference to the service
const firebaseDB = getFirestore(app);
if(firebaseDB){
  console.log(firebaseDB)
}
export default firebaseDB;
'use client';

import usePlaylistTrackContext from '@/app/create-playlist/PlaylistTrackProvider';
import Image from 'next/image';
import { useState } from 'react';
import firebaseDB from '@/app/firebase/firebasedb';
import { collection, addDoc } from 'firebase/firestore';
import Button from '@/components/Button';

const MyPlaylistTable = () => {
  const [playlistName, setPlaylistName] = useState('');

  const { playlistTracks, setPlaylistTracks } = usePlaylistTrackContext();

  function deleteTrack(track) {
    const updatedPlaylistTracks = playlistTracks.filter((items) => items.id !== track.id);
    setPlaylistTracks(updatedPlaylistTracks);
  }

  async function createPlaylist() {
    try {
      console.log('createPlaylist');
      const docRef = await addDoc(collection(firebaseDB, 'playlists'),{
        playlistName: playlistName,
        tracks: playlistTracks,
      });
      console.log('Document written with ID:', docRef.id);
    } catch (e) {
      console.error('error adding document', e);
    }
  }

  return (
    <article>
      <div className="flex items-center gap-2 mb-3">
        <input
          className="text-3xl font-bold placeholder-white bg-transparent border-none"
          type="text"
          required
          placeholder="Playlist Title"
          value={playlistName}
          onChange={(e) => setPlaylistName(e.target.value)}
        />
        <Button className="px-2 py-1 text-xs text-bold w-30" onClick={createPlaylist}>
          save
        </Button>
      </div>
      {playlistTracks.map((track) => (
        <div className="relative flex flex-row px-2 py-3" key={track.id}>
          <Image className="mr-3" src={track.img} width={40} height={40} alt="track image" />
          <div>
            <p className="font-bold">{track.name}</p>
            <p className="text-sm font-semibold text-[#B3B3B3]">{track.artist}</p>
          </div>
          <div className="absolute text-right top-5 text-[#B3B3B3] text-sm right-48">
            {Math.floor(track.duration / 60000)}:
            {((track.duration % 60000) / 1000).toFixed(0).padStart(2, '0')}
          </div>

          <button className="absolute right-10 top-5" onClick={() => deleteTrack(track)}>
            delete
          </button>
        </div>
      ))}
    </article>
  );
};

export default MyPlaylistTable;

I have double-checked for any typos in the code and ensured that the Firestore page is accessible.

Answer №1

After some troubleshooting, I managed to find the solution. Turns out it was a straightforward issue - all I needed to do was define the environment variables in my .env file using uppercase letters.

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

Null value arising due to AJAX's asynchronous nature

I am facing an issue with a form that includes a select option displaying various choices. My goal is to retrieve the selected option and display it in a text box. The options are loaded using AJAX from an XML data source. When attempting to grab the sele ...

Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next. Initially, I considered calculating the time until each pers ...

Checking the URL in Redux Form

I am currently using the redux-form library to manage my form in React Redux. I have successfully implemented validation for fields like email and name. However, I am facing an issue with validating a URL field in redux-form. What specific format should I ...

How can I adjust the time in a range slider using AngularJS?

Currently, I am utilizing a Slider with draggable range in angular js for time selection. The Slider can be found here: https://jsfiddle.net/ValentinH/954eve2L/. I aim to configure the time on this slider to span from 00.00 to 24.00, with a 10-minute inter ...

Using JavaScript regex to match repeating subgroups

Can a regular expression capture all repeating and matching subgroups in one call? Consider a string like this: {{token id=foo1 class=foo2 attr1=foo3}} Where the number of attributes (e.g. id, class, attr1) are variable and can be any key=value pair. C ...

The issue with Next.js getStaticProps is that it is not functioning as expected and is returning an

I'm attempting to retrieve data from an API using getStaticProps, but I am facing an issue where the data returned to my component is undefined. Here is the code for the function: export async function getStaticProps() { const res = (await fetch(&q ...

Tally up various figures in all tables

I am dealing with a dynamic table generated from a PHP loop. Below is an example of the table structure extracted from the browser source code: <table class="table"> ... (table content) </table> <table class="table"> ... (t ...

The object NativeModules from the 'react-native' requirement is currently empty

At the top of one of the node_modules utilized in my project, there is a line that reads: let RNRandomBytes = require('react-native').NativeModules.RNRandomBytes However, I've noticed that require('react-native').NativeModules ...

$scope variables, ng-hide/show directive

There seems to be a confusion with $scope in my code. I have ng-hide/shows that use a variable in the top nav, controlled by "NavController". Inside an ng-view, controllers are linked via the app config function. The appointment setting functionality is ha ...

How do I initiate a custom button click event in React from an event handler in another component?

I have a unique React application that utilizes the Material UI framework for its user interface design. Specifically, I have developed a specialized button component that customizes the default Material UI button and integrates with Redux. Within the ren ...

``When you click, the image vanishes into thin

Could you please explain why the image disappears once I close the lightbox? Access with password: chough ...

Is there a way to access the props value for children beyond the scope of a React

I am trying to add a new class to the Panel element if any of its children have the 'active' class. How can I add the 'parent-active' class if a child element gets the 'active' class? Thank you for your assistance! const MyCo ...

The shopping cart is unable to display the name property as it is undefined

I'm currently working on creating a basic shopping cart using JavaScript. $('.addToCart').click(function(event) { event.preventDefault(); var name = $(this).data('name'); var price = Number($(this).data('price')); ...

Obtaining information using adaptive paths in next.js

Just getting started with next.js and currently working on creating a product page from a catalog. On the catalog page, I am fetching data from the server: // src/app/products/page.tsx import React from "react"; import ProductsPageScene from &quo ...

During the rendering process, a referenced computed property is not defined on the instance

Description: In my child component, I am working with an array called expenseButton that is passed as props. The array contains objects with values which I need to calculate the sum of using the array.reduce() method. Issue: While I can successfully get ...

Rendering DataTable content seamlessly from a different webpage using JavaScript without sacrificing control

Is it possible to dynamically call HTML content from Page2.html into Page1.html by utilizing DataTables (https://datatables.net/)? Page1.html <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" c ...

Exploring the Possibilities of Client-Side Cookie Access in Next JS

Utilizing the cookies-next module, as indicated in their documentation, accessing cookies on the client side is as straightforward as getCookie('key'); - client side Within my Next JS application, I have a basic function: const handleAddToCart ...

Ways to verify the presence of an item in a MonoDB array

My MongoDB model looks like this: const userSchema = new Schema = ({ name: { type: String }, company: [ companyId: { type: String, }, movies: [ { genre: { type: String, enum: [ ...

After several interactions, the CSS files fail to load

I'm currently utilizing jQuery Mobile with 3 pages, and I've noticed that after navigating between the pages, the CSS is not being rendered properly. LoadCss.js $(document).on("pageinit",function(event) { $("#categoriesPage").on('pages ...

Is it necessary to invoke verifyIdToken() while implementing custom claims in callable functions?

While the documentation for Custom Claims states that ID tokens should be verified on every call, the documentation for callable functions suggests that the tokens are automatically verified. It seems that the custom claims documentation is referring to " ...