skip to Main Content

I am having the problem hereafter within a nextJS app that I created on Firebase.

I have some data stored in a realtime DB and I want to make a component to read it.

This is my firebase/config.js :

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 previously used this configuration to write the data to the DB.

And this is the component I am trying to make to read the data:

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

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

  // Attach an asynchronous callback to read the data at our DB reference:
  dbRef.on('value', (snapshot) => {
    console.log(snapshot.val());
  }, (errorObject) => {
    console.log('The read failed: ' + errorObject.name);
  }); 

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

The problem is that I get this error message:

Property 'on' does not exist on type 'DatabaseReference'.

Can someone see what I am doing wrong and how I could solve this issue ?

2

Answers


  1. Since you do import { ref } from "firebase/database"; you use the modular version of the JS SDK.

    You should then do as follows:

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

    The code in your question is for the namespaced JS SDK (prior to V9). More details in the documentation.

    Login or Signup to reply.
  2. I think you’re mixing the implementation of Firebase JS SDK Web modular API with Web namespaced API.

    Let’s say you have the following database structure:

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

    If you wish to listen for any changes in Restaurants database or any path, you may use the following:

    import { firebaseDatabase } from '../firebase/config';
    import { ref, onValue } from "firebase/database";
    
    export default function Home() {
    
      const dbRef = ref(firebaseDatabase, 'Restaurant');
      onValue(dbRef, (snapshot) => {
        const data = snapshot.val();
        console.log(data);
      });
    
    }
    

    Note that onValue method is triggered once when the listener is attached and again every time the data, including children, changes. See this documentation to know the best practices for reading data from Realtime Database.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search