Data not added to firebase realtime database - javascript

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.

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.

How do I write data to my firebase database

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>

Next Js cant find Service messaging (firebase-cloud-messaging)

Hi I using firebase cloud messaging in next js project and when I try to run or build my project I get this error :
info - Checking validity of types
info - Creating an optimized production build
info - Compiled successfully
info - Collecting page data ...node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^
Error: Service messaging is not available
at Provider.getImmediate (file:///I:/Work/Web/Php/Project/wamp/www/test/node_modules/#firebase/component/dist/esm/index.esm2017.js:147:23)
at getMessagingInWindow (I:\Work\Web\Php\Project\wamp\www\test\node_modules#firebase\messaging\dist\index.cjs.js:1460:74)
at I:\Work\Web\Php\Project\wamp\www\test.next\server\pages_app.js:117:83 {
type: 'Error'
}
my code :
it seems this problem happens because using getMessaging
firbase.js
import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from "firebase/messaging";
var firebaseConfig = {
apiKey: "----",
authDomain: "---",
projectId: "---",
storageBucket: "---",
messagingSenderId: "---",
appId: "---",
measurementId: "---"
};
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
export const fetchToken = (setTokenFound) => {
return getToken(messaging, {vapidKey: '---'}).then((currentToken) => {
if (currentToken) {
console.log('current token for client: ', currentToken);
setTokenFound(true);
// Track the token -> client mapping, by sending to backend server
// show on the UI that permission is secured
} else {
console.log('No registration token available. Request permission to generate one.');
setTokenFound(false);
// shows on the UI that permission is required
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// catch error while creating client token
});
}
export const onMessageListener = () =>
new Promise((resolve) => {
onMessage(messaging, (payload) => {
resolve(payload);
});
});
firebase-messaging-sw.js
// Scripts for firebase and firebase messaging
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-messaging-compat.js');
// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
apiKey: "----",
authDomain: "---",
projectId: "---",
storageBucket: "---",
messagingSenderId: "---",
appId: "---",
measurementId: "---"
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function(payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
_app.tsx
import {fetchToken,onMessageListener} from '../tools/firebase'
const [notification, setNotification] = useState({title: '', body: ''});
const [isTokenFound, setTokenFound] = useState(false);
useEffect(() => {
fetchToken(setTokenFound)
onMessageListener().then(payload => {
setNotification({title: payload.notification.title, body: payload.notification.body})
console.log(payload);
}).catch(err => console.log('failed: ', err));
}, []);
i had same issue turns out it was firebase v9 issue
using firebase v8 worked for me
npm i firebase#8.2.3
after installing v8 don't forget to change syntax its firebase.initializeApp(firebaseConfig);

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