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

BoostDock, execute tasks exclusively in select workspaces

Here is the breakdown of my workspaces: apps web-1 (next) web-2 (next) web-3 (next) packages pack-1 (ui) pack-2 (react utils) pack-3 (node utils) services service-1 (express) service-2 (express) service-3 (express) service-4 (express) I am looking ...

Error Encountered in Reactjs: TypeError When Looping Through State Array to Render JSX Component

Currently in the process of constructing a gallery view showcasing cards that are populated with images fetched through an axios API call. The API call is made within a useEffect hook and the resulting object is then stored using useState. However, when ...

Parcel React component library throws an error stating that "require is not defined

Error message: Uncaught ReferenceError: require is not defined at index.js?5WdmUIncGTkIrWhONvlEDQ:1:1 (anonymous) @ index.js?5WdmUIncGTkIrWhONvlEDQ:1 First lines of index.js: require("./index.css"); var $cI6W1$lodash = require("lodash&q ...

Creating an object that tracks the frequency of each element from another object using JavaScript

I have a scenario where I need to create a new object based on the number of occurrences of specific minutes extracted from a timestamp stored in another object. Existing Object: { "data": { "dataArr": [ { ...

Getting the input from an HTML editor and inserting it into a textarea using JavaScript

Currently, I am in the process of developing an HTML editor for a project. I have downloaded a program online that I am attempting to customize according to my requirements. However, I am encountering difficulties when trying to retrieve the inner HTML of ...

Avoid the issue of having duplicate user ids by implementing a locked thread feature within Next.js

My database setup involves using MongoDB to store user data, with the user id incrementing each time a new user registers (e.g. 1, 2, 3, 4, etc). To generate the user id, I have the following code snippet. The collection where user data is stored is named ...

Steps for adjusting the matMenuTriggerFor area so it only triggers when hovering over the arrow

Hello there! I'm currently working on adjusting the trigger area for opening the next menu panel. Right now, the next menu panel opens whenever I hover over either the title or the arrow. However, my goal is to have the menu open only when I hover ove ...

WebDriver encounters difficulty clicking on a certificate error popup window

Currently, I am using webdriver 2.40.0 in C# to interact with my company's website. The issue arises when I encounter a certificate error page while trying to access certain elements. Specifically, after clicking the override link and entering some in ...

Encountering the "Error: JSON.parse: unexpected character" when trying to retrieve JSON data using AngularJS

I've been struggling with this issue for the past few days. Every time I attempt to fetch a JSON object using Angular's $http.get method, I encounter the error message "Error: JSON.parse: unexpected character". The JSON data is generated using P ...

Transitioning from using lerna to adopting pnpm

We are in the process of transitioning our project from Lerna to PNPM and we currently have a script that we run. Here are the commands: "postinstall": "npm run bootstrap" "bootstrap": "lerna bootstrap --hoist", &quo ...

The MaterialUI Datagrid is throwing an error message for an Invalid Hook Call

Having a strange issue with my simple component. I've imported DataGrid from MaterialUI, defined variables for columns and rows, and rendered the DataGrid in a functional component. However, I'm getting an "invalid hook call" error. Most solution ...

I'm experiencing an issue with loading the GeoJSON file on my localhost

I included this vector into my local host code, but the JSON file does not seem to load. geojson_layer = new OpenLayers.Layer.Vector("features", { projection: epsg4326, strategies: [new OpenLayers.Strategy.Fixed()], pro ...

Vue's TreeView component has been encountering issues with accurately displaying the contents of sub

Currently working on creating a customized TreeView in Vue. Check out my progress in the code here. The issue I'm facing is that the subfolders' content (such as child folder 1) is not displaying correctly. Additionally, collapsing the subfolder ...

Struggling to transfer a specific row from a grid to a fresh window in extjs

My goal is to send the selected row from a grid panel to a new window when the user clicks the edit button or double-clicks the row. However, I am encountering difficulties in sending the data. Below is the code for my grid panel (List.js): Ext.define(&a ...

Php/JavaScript Error: Identifier Not Found

I've double-checked my code multiple times, but it still doesn't seem to be working properly. When the PHP runs, the browser console displays the following error: Uncaught SyntaxError: Unexpected identifier. I'm not sure if this is a si ...

Navigating Parent Menus While Submenus are Expanded in React Using Material-UI

My React application includes a dynamic menu component created with Material-UI (@mui) that supports nested menus and submenus. I'm aiming to achieve a specific behavior where users can access other menus (such as parent menus) while keeping a submenu ...

I am facing an issue where my localhost keeps redirecting multiple times due to the combination of NextJs 13

Although everything seems to be working perfectly, there is one issue where once I am logged in, I get redirected to the "/" page. Even if a user tries to access the "/login" or "/register" pages after being logged in, they should still be redirected to th ...

Determine the presence of an image by using a wildcard in the URL

I need to show an image, and if it doesn't exist I want to display a default image. The challenge is that the image can come with any extension. Can someone suggest how I can modify the $.get() function in the code snippet below to make it search for ...

Turn off Chrome 69's autofill functionality

I've recently encountered an issue with Chrome's password autofill feature that has been troubling me for a few days now. This problem began when I was using Chrome version 69. After much trial and error, I found a solution by removing the id an ...

Combining Multiple Arrays into One | Node.js

Can someone explain how to merge an array of arrays to me? For instance, I have the following array: [ [ {brand: 'fiat', model: 'palio'} ], [ {brand: 'nissan', model: 'march'} ] ] I want to transform this array int ...