How do I write data to my firebase database - javascript

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", "test#gmail.com");
</script>

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", "test#gmail.com");
</script>

Related

.then((userCredential) => { } not working with firebase authentification

I am working on a web application (beginner level) and I use firebase for authentification and database. I can create a new account and register it on my firebase authentification dashboard without issue, but nothing inside .then((userCredential) => { } is working (alerts don't show up, I can't register the account on firebase database etc....
I checked on chrome console and no errors show up, and I have no error messages from .catch as well.
How can I fix this so what's inside .then is working?
Thank you!
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js'
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js'
import { getFirestore, doc, getDoc, getDocs, collection } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
const auth = getAuth();
const database = getDatabase()
submitData.addEventListener('click', (e) => {
var name = document.getElementById('full_name').value
var email = document.getElementById('email').value;
var password = document.getElementById('psw').value;
alert(email)
// do verification
// Move on with Auth
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user
alert("user created")
})
.catch(function(error) {
// Firebase will use this to alert of its errors
var error_code = error.code
var error_message = error.message
alert(error_message)
alert('not working')
})
})
If you're using form element then just use e.preventDefault() to stop page from reloading, place it before the variables.

Unable to change notification title in Firebase Cloud Messaging

I am now able to implement push notifications with Firebase Cloud Messaging, and the push notifications themselves are delivered, but I am having trouble changing their content.
The default title is "This site has been updated in the background", but I changed it to any text.
Environment
Vue CLI
TypeScript
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './registerServiceWorker'
import firebase from 'firebase/compat/app';
import { getMessaging, getToken } from "firebase/messaging";
const firebaseConfig = {
apiKey: "xxx",
authDomain: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const app = createApp(App)
installElementPlus(app)
app
.use(store)
.use(router)
.component('MqResponsive', Vue3Mq.MqResponsive)
.mount('#app')
const messaging = getMessaging(firebaseApp);
const vapidKey = {
vapidKey:
"xxx",
};
// Messaging
getToken(messaging, { vapidKey: 'xxx' }).then((currentToken) => {
if (currentToken) {
// Send the token to your server and update the UI if necessary
console.log("currentToken : ", currentToken);
// ...
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
firebase-messaging-sw.js
import firebase from 'firebase/compat/app';
import { onBackgroundMessage } from "firebase/messaging/sw";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "xxx",
authDomain: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
const vapidKey = {
vapidKey:
"xxx",
};
// Messaging
getToken(messaging, { vapidKey: 'xxx' }).then((currentToken) => {
if (currentToken) {
// Send the token to your server and update the UI if necessary
console.log("currentToken : ", currentToken);
// ...
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
// ...
});
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
self.addEventListener('push', async function (event) {
event.waitUntil(
self.registration.showNotification('title', {
body: 'body'
})
);
});
});
The image is localhost, but deploying to the web did not change the result.
I also tested on Firebase Messaging and downloaded as a PWA and again the results did not change.
What is the problem??
Thank you in advance!

Data not added to firebase realtime database

I have a VueJS application and a firebase project, I'm trying to access the realtime database to add data to it but it's not working and it's not logging anything.
I have a firebase.js file :
import firebase from 'firebase/compat/app'
const firebaseConfig = {
apiKey: "myapp",
authDomain: "myapp.firebaseapp.com",
projectId: "myapp",
storageBucket: "myapp",
messagingSenderId: "myapp",
appId: "myapp"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
export default firebaseApp;
And i have this create user method in a file called DataService.js :
import firebase from "../firebase";
import 'firebase/compat/database';
const db = firebase.database();
create(user) {
db.ref('users' + user.login).set({
username: user.login,
email: user.password,
profile_picture : false
},(error)=>{
if(error){
console.log(error)
}else{
console.log('all good');
}
});
}
In my component, I have a method called SaveUser that i'm calling in the submit
saveuser(){
var data = {
login: this.login,
password: this.password,
isvalid: false
};
DataService.create(data);
},
What am I doing wrong ? I'm new to firebase and I don't really know what's not working
Your firebaseConfig variable is missing a databaseURL property, which is pretty much the only key that is required for your code to be able to find the Realtime Database on the server. So add that key/value, and try again.

FireBase + React: TypeError: user.getToken is not a function

Here is the code signInWithEmailAndPassword works perfectly but when I try to acquire a token the error is always thrown TypeError: user.getToken is not a function.
import app from "./base.js";
app.auth()
.signInWithEmailAndPassword(email, password)
.then(function (user) {
user.getToken().then(function (token) {
localForage.setItem("token", token); // store the token
console.log("pusing forward");
history.push("/");
});
}).catch((error) => {
console.log("err: " + error);
});
base.js
import firebase from "firebase/app";
import "firebase/auth";
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_KEY,
authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
});
export default app;
Comments welcome thanks.
According to the API documentation for signInWithEmailAndPassword() user is a UserCredential object. It doesn't have a getToken method. Perhaps you want to use its user property to get a User object, which has a getIdToken() method.
user.user.getIdToken().then(token => { ... })
Here is a peak at the object user1 returned after calling signInWithEmailAndPassword(email, password)

How can I import data from Firestore to a Vue CLI project?

I am trying to import data from a Firestore Database into a Vue CLI project but can not get it to work.
I have followed several tutorials and my version never works. It seems I have a problem retrieving the data each time I try, as my console.log shows nothing.
I have the following in a JS file (index.js which lives in a folder called db - Plus for security, I have removed the content in quotations for here on Stackoverflow);
import firebase from "firebase";
import "firebase/firestore";
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
firebase.initializeApp(config);
const db = firebase.firestore();
db.settings({ timestampsInSnapshotps: true });
Then in my component I have the below;
import db from '#/db'
export default {
name: 'HelloWorld',
data () {
return {
cafes: []
}
},
created () {
db.collection('cafes').get().then((snapshot) => {
console.log(snapshot.docs);
});
}
}
I have read that I nolonger need the db.settings({ timestampsInSnapshotps: true }); However, when I remove this it errors in the terminal and browser.
Template as below;
<template>
<div class="cafes">
<h1>Here are some cafés</h1>
<div for="cafe in cafes" v-bind:key="cafe.name">
<div>
{{cafe.name}}
</div>
</div>
</div>
</template>
Any help welcome as I have been trying for days.
Do as follows:
Adapt your Firebase db/index.js as follows:
import firebase from 'firebase'
import 'firebase/firestore'
// firebase init goes here
const config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
}
firebase.initializeApp(config)
const db = firebase.firestore()
// firebase collections
const cafesCollection = db.collection('cafes')
export {
db,
cafesCollection
}
Adapt your Component as follows:
const firebase = require("../db/index.js"); // Adapt the path as desired
export default {
name: 'HelloWorld',
data () {
return {
cafes: []
}
},
created () {
firebase.cafesCollection.get().then((snapshot) => {
console.log(snapshot.docs);
let cafesArray = [];
snapshot.forEach(doc => {
cafesArray.push({id: doc.id, ...doc.data()});
});
this.cafes = cafesArray;
})
.catch(error => {
console.log(error);
})
}
}

Categories