Issue with nextJS/Firebase database while experimenting with enabling web frameworks

I encountered an issue with a nextJS app I built on Firebase, following the steps and running the commands mentioned below:

 % npx create-next-app@latest
 % cd myapp
 % firebase experiments:enable webframeworks
 % npm install -g firebase-tools
 % firebase init hosting
 % firebase deploy
 % npm i firebase

 % firebase --version
13.4.1

This is the content of app/page.tsx:

 % cat app/page.tsx 
import Image from "next/image";
import LoadData from './components/loadData'

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      Where shall we go ?
      <LoadData/>
    </main>
  );
}
 % 

Here is the content of app/components/loadData.tsx:

 % cat app/components/loadData.tsx 
import { useState, useEffect } from 'react';
import firebase from 'firebase/compat/app';

export default function LoadData() {
  // const dbRef = firebase.database (This produces no error)
  const dbRef = firebase.database()
  //const dbRef = firebase.database().ref('Restaurant')//.child('Adventure')
  /*dbRef.push().set({
    name: 'My favorite one',
    phone: '00-6969-1122',
    station: '2nd Street North"'
  })*/

  return (
        <div>
      LoadData
        </div>
  )
} /* End of LoadData */
 % 

And here's the file (initFirebase.tsx):

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

// Note about the following. To be able to log in, only the apiKey is necessary.
// The rest of the information is only useful to access the database.
const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_WEB_API_KEY,
  projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
  databaseURL: process.env.NEXT_PUBLIC_DATABASE_URL
};

firebase.initializeApp(firebaseConfig);

export default firebase;

export {firebaseConfig}

Upon executing the command:

% firebase deploy

This was the response received:

.......
TypeError: e$.database is not a function
......
> Export encountered errors on following paths:
    /page: /

Error: An unexpected error has occurred.

After some experimentation, I identified that this line:

const dbRef = firebase.database()

is causing the issue. However, I am unsure how to address it.

Any assistance or relevant guidance would be greatly appreciated.

(Ultimately, my goal is to successfully access my realtime database for read/write operations)

Answer №1

Start by setting up and using Firebase products by creating a folder called firebase and adding a file named config.js

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";

const firebaseConfig = {
    apiKey: "...",
    authDomain: "...",
    databaseURL: "...",
    projectId: "...",
    storageBucket: "...",
    messagingSenderId: "...",
    appId: "..."
  };

const firebaseApp = initializeApp(firebaseConfig);
export const firebaseDatabase = getDatabase(firebaseApp);

In your component, utilize the Firebase product instance imported from firebase/config.js and bring in any other necessary methods or modules from the Firebase SDK

import { firebaseDatabase } from '../firebase/config';
import { push, ref } from "firebase/database";

export default function Home() {

  const writeData = () => {
    push(ref(firebaseDatabase, 'items'), {
      name: "itemName"
    });
  }

  return (
    <button onClick={writeData}>Write Data</button>
  )
}

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

Verify the occurrence of an element within an array inside of another array

Here is the scenario: const arr1 = [{id: 1},{id: 2}] const arr2 = [{id: 1},{id: 4},{id: 3}] I need to determine if elements in arr2 are present in arr1 or vice versa. This comparison needs to be done for each element in the array. The expected output sho ...

Unable to display information from a repeated `textarea` in ngRepeat

Check out my code on Plunker: https://plnkr.co/edit/rBGQyOpi9lS0QtnCUq4L I'm trying to log the content of each textarea when typing, using the printStuff() function: $scope.printStuff = function(customize, item) { console.log(customize[item.inde ...

What is the best way to connect a series of checkboxes within a form utilizing Angular?

I created a form with checkboxes that allow users to select multiple options. However, when I submit the form, instead of receiving an array of objects representing the checked checkboxes, I'm not getting anything at all. Here is what I see in the co ...

Implement a select element with an onchange event that triggers an AJAX

As a newcomer to Javascript, I've been struggling to find a solution to my issue. The goal is to add an additional select option when the previous select option is changed. I attempted to implement the code below, but it's not functioning correct ...

Managing a form containing delicate information that will not be sent until at least one hour

Currently, I am utilizing next js to create a project for my basketball league. The main objective is to manage games, players, statistics, and more. However, I am encountering difficulties when it comes to implementing the submission of game stats. In par ...

Encountering an error stating "Argument of type 'X' is not assignable to parameter of type 'X' in the NextApiResponse within NextJS."

Here is the code snippet I am working with: type Data = { id: string; name: string; description: string; price: number; }; const FetchMeals = async (req: NextApiRequest, res: NextApiResponse<Data>) => { const response = await fetch( ...

The installation of the material ui package was unsuccessful

C:\Users\User\Desktop\client4>npm i @material-ui/icons npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] ...

Assign the default value of a Vue prop to the options of its parent component

I have a child component that needs to accept a value given in the component's parent's $options object as a possible default value. In the background, the component should be able to receive its data through a prop or from a configuration. Howe ...

Error: PHP is showing an undefined index error when trying to decode JSON, even though the value

I am feeling quite puzzled. I transferred a key value pair object from jQuery to PHP and successfully alerted it back out. However, when I visit the PHP page, it indicates that the data is either null or an undefined index. Here is my jQuery code: $(&ap ...

Trick to bypass inline script restrictions on Chrome extension

I have developed a Chrome extension with a feature that involves looping a list of links into a .div element. Here is the code snippet: function updateIcd() { modalIcdLinks.innerHTML = ''; let icdLinks = ''; for (let i = 0; i < icd ...

What is the proper way to insert a line break within a string in HTML code?

Trying to simplify my code, I've turned to using Nunjucks to pass a group of strings to a function that will then display them. This is what it looks like: {% macro DisplayStrings(strings) %} {% for item in strings %} <div>{{ item.strin ...

Tips for populating a textfield with data from a <select> dropdown using javascript

Is there a way to populate a textfield with data automatically based on information provided in the tab, utilizing JavaScript? Additionally, is it possible to prevent the filled data from being edited? The textfield should be able to dynamically fill data ...

Highlighting the current menu item by comparing the URL and ID

Looking to make my navigation menu items active based on URL and ID, rather than href. None of the suggested solutions (like this one, this one, or this one) have worked for me. This is how my Navigation is designed: <nav id="PageNavigation"& ...

Guide to swapping images based on conditions using Angular JS

I am trying to display an image based on data received from an API response instead of text. If the value is true, I want to show an access symbol. If the value is false, I want to show a deny symbol. However, when attempting this, I am only getting th ...

Refreshing AJAX content with a dynamically adjusting time interval

I am facing a scenario where I have a webpage featuring a countdown alongside some dynamic data refreshed via AJAX. To optimize server load, I found a clever solution by adjusting the AJAX refresh interval based on the time remaining in the countdown, foll ...

How to fetch select element within a table by using jQuery

I encountered a situation where I have a table element with a select element inside its td. The id of the table (in this example, it is "table1") could potentially change. So my query is, how can I retrieve the selected option using the table ID in JQuer ...

React-highlightjs failing to highlight syntax code properly

I'm currently using the react-highlight library to highlight code snippets in my next.js application. However, I've encountered an issue with the code highlighting when using the a11y-dark theme. https://i.stack.imgur.com/ip6Ia.png Upon visitin ...

Unable to navigate a simulated scrollbar

As someone who is new to web development, I am embarking on the journey of building a UI Grid that can effectively display a large amount of data. My goal is to implement a scrollbar that allows for horizontal scrolling across approximately 1,000,000 data ...

Every time I attempt to serve Firebase functions, it alerts me that the port is closed

While attempting to run my firebase function, I encountered a persistent error message that reads: Error: Port {{Port Here}} is not open, could not start functions emulator.. Despite trying different ports, I have been unable to resolve this issue. I' ...

Incorporate additional plugins into React-Leaflet for enhanced functionality

I'm currently working on developing a custom component using react-leaflet v2, where I aim to extend a leaflet plugin known as EdgeMarker. Unfortunately, the documentation provided lacks sufficient details on how to accomplish this task. In response, ...