简体   繁体   中英

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 }); }

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
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM