scorval
scorval

Reputation: 57

firebase.getDatabase()).ref() is not a function

Hello I'm doing a project shcool on nodeJS and work with firebase. I try to get the name of a users to not rewrite an existing value. the db is:

the db

my code to try something:

serv.js

const firebaseConfig = {
  apiKey: process.env.REACT_APP_API_KEY,
  authDomain: process.env.REACT_APP_AUTHDOMAIN,
  databaseURL: process.env.REACT_APP_DATABASEURL,
  projectId: process.env.REACT_APP_PROJECTID,
  storageBucket: process.env.REACT_APP_STORAGEBUCKET,
  messagingSenderId: process.env.REACT_APP_MESSASGINGSENDERID,
  appId: process.env.REACT_APP_APPID,
  measurementId: process.env.REACT_APP_MEASUREMENTID
};

const {initializeApp} = require('firebase/app');
const {getDatabase} = require('firebase/database');
const {getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword} = require('firebase/auth');

const fireapp = initializeApp(firebaseConfig);
const db = getDatabase(fireapp);
var firebaseauth = getAuth(fireapp);
[...]

function create_entry_name(name, email)
{
  const ref = db.ref('/users/' + name);

  ref.on('value', (snapshot) => {
    console.log(snapshot.val());
  }, (errorObject) => {
    console.log('The read failed: ' + errorObject.name);
  });
}

that's litteraly the example on the firebase website.

But I get an error witch is:

db.ref is not a function

I will really be thanks full if you have an solution for this problem...

Upvotes: 3

Views: 3037

Answers (3)

Dharmaraj
Dharmaraj

Reputation: 50830

You are using Modular SDK (v9.0.0+) but using syntax of older name-spaced syntax. Try refactoring the code as follows:

import { getDatabase, ref, onValue} from "firebase/database";

function create_entry_name(name, email) {
  const ref = ref(db, '/users/' + name);

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

You can find more details about the new syntax in the documentation.

Upvotes: 3

danh
danh

Reputation: 62686

Build the app from the app library...

import { firebaseApp } from 'firebase/app';
const app = initializeApp({/*config*/});

Then get the database from the initialized app. Note that the OP fails to pass a param to getDatabase...

const db = getDatabase(app);

const ref = db.ref('users/' + name);
// etc...

Upvotes: 0

Patrick Kelly
Patrick Kelly

Reputation: 1009

Call the getDatabase directly. It's already initialized.

const db = getDatabase();
const ref = db.ref('/users/'+ name);

Upvotes: 0

Related Questions