How to store data in the firebase realtime database - javascript

i need to store some simple data on the firebase realtime database, i've connected my app to the firebase realtime database, and imported all the requirments in the javascript file, but whenever my code is done, i check the realtime database and find that nothing is stored, i've followed many tutorials on youtube, even the firebase tutorial on youtube, but the mentionned problem stays, the realtime database stays empty as if i didn't write any code.
Here is the javascript code :
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, set } from 'firebase/database';
const firebaseConfig = initializeApp({
apiKey: "AIzaSyChK5qg7AJi0_AZQAc2iWnvDVJjyJvz5iI",
authDomain: "mycoolapp-4373a.firebaseapp.com",
databaseURL: "https://mycoolapp-4373a-default-rtdb.firebaseio.com",
projectId: "mycoolapp-4373a",
storageBucket: "mycoolapp-4373a.appspot.com",
messagingSenderId: "895684408479",
appId: "1:895684408479:web:3341db270dcd768e085eaa"
});
const app = initializeApp(firebaseConfig);
function writeUserData(userId, username, email, message) {
const db = getDatabase();
const reference = ref(db, 'users/' + userId);
set(reference, {
username: username,
email: email,
message: message
});
}
writeUserData("andrew","andrew__8","andrew#gmail.com", "hey..i'm andrew!!");
is there any other working way ?

Related

Shuffle docs from firebase firestore collection in JavaScript

Randomizing content may be a useful functionality for different applications. The following code completes the task for a firebase firestore collection.
Sample firebase initialization main shuffle code below
// Import Firebase
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-app.js";
import { doc, getDoc, getDocs, collection, getFirestore } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-firestore.js";
// Firebase Config
const firebaseConfig = {
apiKey: "your-info",
authDomain: "your-info",
databaseURL: "your-info",
projectId: "your-info",
storageBucket: "your-info",
messagingSenderId: "your-info",
appId: "your-info",
measurementId: "your-info"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Firestore
const firestore = getFirestore(app);
Code to get a sample 'contributions' collection and console log shuffled docs:
// Get Collection
const contributionsCollection = collection(firestore, 'contributions');
// Get Collection Docs
const contributionsCollectionDoc = await getDocs(contributionsCollection);
// Fill in Contributions
if(contributionsCollectionDoc.empty == false) {
var contributions = contributionsCollectionDoc.docs;
shuffle(contributions);
contributions((doc) => {
console.log(doc.data());
});
}

Client is Offline error while using firebase realtime database

I am trying to make a small database system for my client that will capture his website's registered users name and there spent amount. Based on there spent amount he will get some gifts.
Using firebase realtime database i am able to store user spent amount but when i try to get data from database. I am getting the following Error from the line:
get(child(userDbRef, "User-ID-"+userID)):
"Uncaught (in promise) Error: Error: Client is offline."
initailData(); will work if user does not have data stored already and if the data has been stored once then runInitialFunction(); will work and get/retrieve data from database.
Here is my code
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/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: "AIzaSyAfA1HIkamXEFtDidPkpxaltDVsWpFWepE",
authDomain: "thundersmmpanel-77fb2.firebaseapp.com",
databaseURL: "https://thundersmmpanel-77fb2-default-rtdb.firebaseio.com",
projectId: "thundersmmpanel-77fb2",
storageBucket: "thundersmmpanel-77fb2.appspot.com",
messagingSenderId: "867306490186",
appId: "1:867306490186:web:93407cb6d8b0e9abe9d9b3"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
//<!--my code-->
import {getDatabase, ref, set, get, child, update}
from "https://www.gstatic.com/firebasejs/9.6.0/firebase-database.js";
const userID = {{user['id']}};
const userName = "{{user['username']}}";
const pointsDb = getDatabase();
//<!-- initial data -->
function initailData() {
set(ref(pointsDb, "User-ID-"+userID),{
UserName: userName,
InitialSpent: {{user['spent']}},
ThisRun: 1
})
.then(function(){
alert("Done");
})
.catch(function(error){
alert("Error "+error);
});
console.log("initailData");
}
function runInitialFunction() {
const userDbRef = ref(pointsDb)
get(child(userDbRef, "User-ID-"+userID)).then((snapshot)=>{
if(snapshot.exists()){
}else{
initailData();
}
});
console.log("runInitialFunction");
}
runInitialFunction();

Firebase is not defined when connecting to Realtime Database Web

I am trying to connect my Realtime Firebase Database to my Web App and eventually store data in it.
I keep running into the same problem when loading my HTML file. The error I get in the console is Uncaught ReferenceError: firebase is not defined.
This is what my script looks like:
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-analytics.js";
const firebaseConfig = {
apiKey: "<api key>",
authDomain: "<domain>",
databaseURL: "<db url>",
projectId: "<project id>",
storageBucket: "<bucket>",
messagingSenderId: "<id>",
appId: "<app id>",
measurementId: "<id>"
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
var database = firebase.database();
var postListRef = database.ref('posts');
var newPostRef = postListRef.push();
newPostRef.set({
"post1": "testing"
});
</script>
You're importing functions from Firebase using new v9 modular SDK syntax. In that syntax you have top-level functions like getDatabase(), instead of objects like firebase.database().
The equivalent of the Realtime Database code in your snippet is:
var database = getDatabase(app);
var postListRef = ref(database, 'posts');
var newPostRef = push(postListRef);
set(newPostRef, {
"post1": "testing"
});
I recommend keeping the Firebase documentation on reading and writing data, appending data to a list, and the modular upgrade guide handy.
If you have a lot of existing Realtime Database code, you can migrate in steps by importing the compat path first:
import firebase from 'firebase/compat/app';
import 'firebase/compat/database';

Firebase auth not working using Vue and Vuex

I'm trying to add authentication using Firebase in my Vue app, but I'm getting [Vue warn]: Error in v-on handler: "TypeError: _config_firebase__WEBPACK_IMPORTED_MODULE_8__.user.SignInWithEmailAndPassword is not a function" error.
Here is my irebase config file:
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: "MY_API_KEY",
authDomain: "MY_AUTH_DOMAIN",
databaseURL: "MY_DB_URL",
projectId: "MY_PROJECT_ID",
storageBucket: "MY_STORAGE_BUCKET",
messagingSenderId: "MY_MESSAGE_SENDER_ID",
appId: "MY_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Get a Firestore instance
export const user = firebase.auth();
export const db = firebase.firestore();
Then the action in Vuex:
import { db, user } from "./config/firebase";
loginUser({ commit }, payload) {
user
.SignInWithEmailAndPassword(payload)
.then(user => {
console.log(user);
commit("SET_USER", user);
})
.catch(error => {
commit("setLoading", false);
commit("setError", error);
console.log(error);
});
router.push("/");
}
So far, I have been able to Create, Read, Update and Delete, although, the config file was slightly different than this, when I added auth was when I altered the code.
Change this:
user.SignInWithEmailAndPassword(payload)
into this:
user.signInWithEmailAndPassword(payload)
From the docs:
Asynchronously signs in using an email and password.

How to connect an expo app to google firestore?

I am trying to authenticate a user and also organize the users in my database by their uid and then have the data field be by email. The users are successfully being authenticated however nothing appears in my firestore database.
My firestore security rules are in test mode so there should be no issue with permissions. In my action dispatch, I am successfully getting the user from firebase with their uid, access token, and everything else. I believe the error must be some way I am trying to connect to the firestore.
In my app.js file I initialize firebase like this-
import firebase from 'firebase';
import '#firebase/firestore';
componentDidMount() {
const firebaseConfig = {
apiKey: 'xxxxxxxx',
authDomain: 'xxxxxxxxx.firebaseapp.com',
databaseURL: 'xxxxxxxx.firebaseio.com',
projectId: 'xxxxxxxx',
storageBucket: 'xxxxxxx.appspot.com',
messagingSenderId: 'xxxxxxxxxxx',
appId: 'xxxxxxxxxxxxxxxxxxxx'
};
firebase.initializeApp(firebaseConfig);
}
Then this is how I am trying to make the call to put the user into the database-
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((user) =>
dispatch({ type: USER_LOGIN_SUCCESS, payload: user });
const dbRoot = firebase.firestore();
dbRoot.collection('users').doc(user.user.uid).set({ email });
});
Also at the top of that file, I am importing as follows
import firebase from 'firebase';
import '#firebase/firestore';
Again, these users are being successfully authenticated but they are not appearing in the firestore database.
You have to add a collection to the database and add data.
const dbRoot = firebase.firestore().collection('users');
...
addData() {
dbRoot.add({
user: user.user.uid,
email : email,
complete: true,
});
OR
const dbRoot = firebase.firestore().collection('users');
...
const defaultDoc = {
email: email
};
async addData() {
await dbRoot.doc(user.user.uid).set(defaultDoc);
}

Categories