Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

javascript - Firebase SDK is missing database() function

I tried to use the Firebase SDK, but it does not have the database() function required to change, remove, or retrieve data from the server (Firebase Realtime Database). I think I installed the Firebase SDK correctly because when I log firebase after importing it, it shows an object.

I tried the following code:

import React, { Component } from "react";
import classes from "./Body.module.css"
import axios from "../../axios";
import Aux from "../../hoc/Auxiliary/Auxiliary";

import firebase from "firebase/app";
import "firebase/analytics";
import "firebase/auth";
import "firebase/firestore";

const firebaseConfig = { /* ... */ };

firebase.initializeApp(firebaseConfig); 

class Body extends Component{
    state = { /* ... */ }

    setHandler = () => {
        console.log(firebase);
    }
    
    /* ... */
}

After calling the setHandler function, I got this object:

{__esModule: true, initializeApp: ?, app: ?, registerVersion: ?, setLogLevel: ?, …}
INTERNAL: {components: Map(14), registerComponent: ?, removeApp: ?, useAsService: ?, createFirebaseNamespace: ?, …}
SDK_VERSION: "8.0.1"
User: ? Im(a, b, c)
analytics: ? (appArg)
app: ? app(name)
apps: (...)
auth: ? (appArg)
default: {__esModule: true, initializeApp: ?, app: ?, registerVersion: ?, setLogLevel: ?, …}
firestore: ? (appArg)
initializeApp: ? ()
installations: ? (appArg)
onLog: ? onLog(logCallback, options)
registerVersion: ? registerVersion(libraryKeyOrName, version, variant)
setLogLevel: ? setLogLevel(level)
__esModule: true
get apps: ? getApps()
__proto__: Object

As you see, there is no such a field called database, which is what I need. Anyone please have an idea how to fix it?

It must be able to work in the following way:

function writeUserData(userId, name, email, imageUrl) {
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are missing the import for the Realtime Database SDK.

import "firebase/database";

Furthermore, in your writeUserData function, you should return the Promise so that you can properly handle errors (such as trying to modify another user's data).

function writeUserData(userId, name, email, imageUrl) {
  return firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...