1

So I need to write data onto my firebase real time database, it has all read and write enabled but the code (on a web page) does not work?

I have a simple reference to the database and a write function but it gives me the error of app.database() is not a function, which variable am I supposed to reference for it?

<script type="module" src="https://www.gstatic.com/firebasejs/9.8.4/firebase-database.js"></script> <script type="module"> // Import the functions you need from the SDKs you need import { initializeApp} from "https://www.gstatic.com/firebasejs/9.17.1/firebase-app.js"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration const firebaseConfig = { apiKey: "xxx", authDomain: "xxx", projectId: "xxx", storageBucket: "xxx", messagingSenderId: "xxx", appId: "xxx" }; // Initialize Firebase const app = initializeApp(firebaseConfig); function writeUserData(userId, name, email) { app.database().ref('users').set(ref(db, 'users/' + userId), { username: name, email: email }); } writeUserData(1, "tester", "[email protected]"); </script> 

1 Answer 1

1

Import getFirestore and try to reference the firestore database from it.

<script type="module" src="https://www.gstatic.com/firebasejs/9.8.4/firebase-database.js"></script> <script type="module"> // Import the functions you need from the SDKs you need import { initializeApp} from "https://www.gstatic.com/firebasejs/9.17.1/firebase-app.js"; import {getFirestore, collection, addDoc} 'https://www.gstatic.com/firebasejs/9.17.1/firebase-firestore.js' // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration const firebaseConfig = { apiKey: "xxx", authDomain: "xxx", projectId: "xxx", storageBucket: "xxx", messagingSenderId: "xxx", appId: "xxx" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const db = getFirestore(app); async function writeUserData(userId, name, email) { const docRef = await addDoc(collection(db, "users"), { userId, username, email }); } writeUserData(1, "tester", "[email protected]"); </script> 
Sign up to request clarification or add additional context in comments.

10 Comments

it now says db.ref is not a function, also I should mention that this is for the realtime database
You are adding a user into a collection called 'users', right?
Yes I am doing that
I have updated the answer, try to use it now.
it now says 'POST xxxxxxxx net::ERR_BLOCKED_BY_CLIENT'
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.