Encountering difficulties reading data from a database in a Next.js/Firebase application

I am encountering a problem within a nextJS app that I developed on Firebase.

In my realtime DB, I have some stored data that I want to read using a component.

Below is my firebase/config.js file:

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

const firebaseConfig = {
    apiKey: process.env.NEXT_PUBLIC_WEB_API_KEY,
    databaseURL: process.env.NEXT_PUBLIC_DATABASE_URL,
    projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
  };

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

I used this configuration previously to write data to the DB.

Now, I am working on a component to read the data as shown below:

import {firebaseDatabase} from '../../firebase/config';
// (Changed) import {ref} from "firebase/database";
import {onValue,ref} from "firebase/database";

export default function ShowData() {
  const dbRef = ref(firebaseDatabase, 'Restaurant')

  console.log('Test onValue')
  onValue(dbRef, (snapshot) => {
          console.log(snapshot.val())
        },
        (error) => {
          console.log('Error(onValue): '+error);
        }
  );

  return (
        <div>
      <div>ShowData</div>
      {/* ...... */}
        </div>
  )
} /* End of ShowData */

Even though the error message regarding 'Property 'on' does not exist on type 'DatabaseReference' has disappeared after making code changes,

I am still not getting the expected output displayed.

However, I can verify that there are 8 items under Restaurant in my DB.

Can anyone identify what might be going wrong and suggest a solution?

For testing purposes, I've set my rules as follows:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Answer №1

It appears that there may be some confusion between the Firebase JS SDK Web modular API and Web namespaced API.

Consider a database structured as follows:

{
  "Restaurants": {
    "RestaurantID": {
      "name": "Restaurant Name",
      "rating": 5
    }
  }
}

If you want to monitor changes in the Restaurants database or any subpath, you can utilize the following code snippet:

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

export default function Home() {

  const dbRef = ref(firebaseDatabase, 'Restaurants');
  onValue(dbRef, (snapshot) => {
    const data = snapshot.val();
    console.log(data);
  });

}

Keep in mind that the onValue method is initially triggered upon attaching the listener and subsequently whenever there are modifications in the data, including its children. For further guidance on reading data from Realtime Database, refer to this documentation.

Answer №2

When you import { ref } from "firebase/database", you are using the modular version of the JS SDK but your code for listening to Realtime Database data is from the namespaced JS SDK (prior to V9).

To resolve this issue, follow these steps. More information can be found in the documentation.

import { ref, onValue } from "firebase/database"; // <= See onValue

// ...

const dbRef = ref(firebaseDatabase, 'Restaurant')
onValue(dbRef, (snapshot) => {
  console.log(snapshot.val());
  // ...
});

Remember that you can also include a cancelCallback to handle errors:

onValue(
  dbRef,
  (snapshot) => {
    console.log(snapshot.val());
    // ...
  },
  (error) => {
    console.log(error);
  }
);

Answer №3

The challenge you are encountering arises from attempting to utilize the on method with a DatabaseReference object, which does not support this method. Instead, consider using the onValue method provided by the Firebase SDK.

Below is the revised code:

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

export default function DisplayData() {
    const dbReference = ref(firebaseDatabase, 'Restaurant');

    // Add an asynchronous callback to fetch the data at our DB reference:
    onValue(dbReference, (snapshot) => {
        console.log(snapshot.val());
    }, (error) => {
        console.log('Error(onValue): ' + error);
    });

    return (
        <div>
            <div>DisplayData</div>
            {/* ...... */}
        </div>
     );
     } /* End of DisplayData */

Remember that the above code snippet will simply log the data to the console. If you intend to exhibit the data in your component, establish a state variable to store the data and update the state upon data alterations. Here's an example employing React hooks:

import { useEffect, useState } from 'react';
import { firebaseDatabase } from '../../firebase/config';
import { onValue, ref } from 'firebase/database';

export default function DisplayData() {
    const [data, setData] = useState(null);

    useEffect(() => {
        const dbReference = ref(firebaseDatabase, 'Restaurant');

        const unsubscribe = onValue(dbReference, (snapshot) => {
            setData(snapshot.val());
        }, (error) => {
            console.log('Error(onValue): ' + error);
        });

        return () => {
            unsubscribe();
        };
    }, []);

    return (
        <div>
            <div>DisplayData</div>
            {data && (
                <ul>
                    {Object.entries(data).map

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

The submit form and cordova functions are failing to trigger

I am encountering an issue where I cannot successfully call the submitForm() function when attempting to trigger it via ng-submit. The function does not execute as expected. How can I troubleshoot and resolve this problem? (function () { 'use str ...

The vue-croppa component is showing unusual behavior, with an error message stating "Failed to mount component: template or render function not

I recently tried utilizing vue-croppa for image cropping in my project. I installed it using the npm package manager with the command: npm install --save vue-croppa However, when attempting to implement it as usual: import Croppa from 'vue-croppa&a ...

The fs.fsync(fd, callback) function in the node.js API allows you

Can you explain the purpose of fs.fsync(fd, callback) in the Node.js API? fs.fsync(fd, callback) This function is used for asynchronous fsync(2). The completion callback only returns an exception if there is one. fs.fsyncSync(fd) This function is for ...

Is there a way to store the JWT response header retrieved with fetch?

I am currently utilizing React and employing fetch to send a request to the server: fetch("http://localhost:8001/api/login", { method: 'post', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, ...

Utilizing Node.js and Express.js to Parse HTML Form Inputs

Having trouble extracting input from an HTML form and utilizing it in Node.js. Here is the HTML form being used: <form action="/myform" method="POST"> <input type="text" name="mytext" required / ...

Modify the directory (app) within the Next.js app router

Hey there, I am looking to change the default app-router folder (app) in Nextjs I have tried searching for a solution but couldn't find one I want to rename it from: src/app/layout.tsx to src/nextapp/layout.tsx Does anyone know how to do this? I&ap ...

Printing dynamic data

When the print button is clicked, I need to print dynamically generated data from a table that has an ID. The table data (td and tr) is dynamically generated. I have successfully retrieved the table data and attempted to print everything using window.prin ...

Tips for selecting a specific item in a list using onClick while iterating through a JSON array in React

I have a unique JSON file filled with an array of objects, each containing a "Question" and "Answer" pair (I am working on creating an FAQ section). My current task involves mapping through this array to display the list of questions, a process that is fun ...

What might prevent an onSubmit event from triggering the execution of "checkTheForm()"?

Despite consuming a substantial amount of information on the internet, I still find myself puzzled by why my code isn't functioning as expected. I acknowledge that there are numerous tutorials out there guiding me to use <form action="index.html" o ...

Encountering Err_Connection_Refused while working with MVC WebAPI 2 and AngularJS

Seeking guidance on WebAPI, AngularJS, and .NET Authentication, I am currently following a tutorial mentioned HERE. The tutorial is brief (~under 10 mins), but I encountered an error stating Failed to load resource: net::ERR_CONNECTION_REFUSED. Typically, ...

Perform a replacement with jQuery.replaceWith() on an input field and refocus in Microsoft Internet Explorer

There exists a script http://gist.github.com/457324 which establishes default text (extracted from the element's title attribute) for empty input[type=text] as well as input[type=password] elements. However, setting default text for password elemen ...

Acquiring data within a jade template in order to generate static HTML pages

I am struggling to pass data to a jade template in order to generate static content. While I am not well-versed in node.js and express, I use jade as a template engine for creating static html. Many of the requests in the jade issue list pertain to includ ...

Encountered an issue with reading the property childnotes of null during data retrieval using ajax in PHP

Hello, I am encountering an error while trying to fetch data using ajax. The error message is "Cannot read property 'childNodes' of null". Can anyone help me identify what might be wrong with my code? I have created a form to search for data with ...

A valid ReactComponent must be returned in order to properly render in React. Avoid returning undefined, an array, or any other invalid object

While working on my react application, I came across an error that I have been trying to troubleshoot without any success. It seems like I must be overlooking something important that could be quite obvious. *Error: VideoDetail.render(): A valid ReactComp ...

Switch classes according to scrolling levels

My webpage consists of multiple sections, each occupying the full height and width of the screen and containing an image. As visitors scroll through the page, the image in the current section comes into view while the image in the previous section disappe ...

Utilizing Vue Router to leverage specific getters from Vuex

I am currently facing an issue with accessing the authenticated user in my Vuex store within my router.js file. { path: '/admin/login', name: 'admin-login', component: AdminLogin, beforeEnter(to, from, next) { console.log(s ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

Endless repetition occurs when invoking a function within a v-for loop

I've encountered an issue while trying to populate an array using a method, leading to redundant data and the following warning message: You may have an infinite update loop in a component render function. Below is the code snippet in question: ...

Enhance DataTables functionality by including the ability to select which script to execute

Currently, I have a DataTables displayed with the provided code, utilizing server-side processing which is functioning properly. I am interested in implementing a dropdown menu above the table that allows users to select from options such as: Product Gr ...

Creating a ROT13 cipher in JavaScript

In my JS function, I need to handle a variable called i. My goal is to encode this variable using ROT13 before proceeding with the function. The challenge lies in decoding the variable and integrating it into the script. I came across a JavaScript implem ...