How can I retrieve data from my firebase database? - javascript

I have tried many ways to get data from my firebase database, but they dont work.
Is there any simple way to retrieve data from my firebase database?
my js code:
var firebaseConfig = {
apiKey: "REDACTED",
authDomain: "REDACTED.firebaseapp.com",
projectId: "REDACTED",
storageBucket: "REDACTED.appspot.com",
messagingSenderId: "474155068193",
appId: "REDACTED",
measurementId: "G-715TVNY07N"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
console.log(firebase);
var database = firebase.database();
var ref = database.ref('en');
function lah(){
var data = {
kommentti: document.getElementById("viesti").value
}
ref.push(data);
}
my database:
I would like to know what is inside those kommenttis.

If you want to get the data just once without a listener you can use a function like this one:
const getData = async () => {
return firebase
.database()
.ref("en")
.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
const childKey = childSnapshot.key;
const childData = childSnapshot.val();
const kommentti = childData.kommentti;
});
});
};

Related

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.

messaging.requestPermission is not a function

trying to send push notification to app but i need permission from user for that but getting this error that messaging.requestPermission is not a function ,
here is my code for push notification.js file
import * as firebase from 'firebase/app';
import { getMessaging } from "firebase/messaging";
export const initializeFirebase = () => {
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "pushnotification-9b180",
storageBucket: "pushnotification-9b180.appspot.com",
messagingSenderId: "878043563283",
appId: "1:878043563283:web:c2a44f3c8b02ad8a17c6e6",
measurementId: "G-GMWQKL94ZD"
});
}
export const askForPermissionToReceiveNotifications = async () => {
try {
const messaging = getMessaging();
await messaging.requestPermission();
const token = await messaging.getToken();
console.log('Your token is:', token);
return token;
} catch (error) {
console.error(error);
}
}
Here is the screenshot of errorserros
What are you using react-native or react?
but in react-native way you need add this line
import messaging from '#react-native-firebase/messaging';
you don´t need
const messaging = getMessaging();
import * as firebase from 'firebase/app';
import { getMessaging } from "firebase/messaging";
export const initializeFirebase = () => {
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "pushnotification-9b180",
storageBucket: "pushnotification-9b180.appspot.com",
messagingSenderId: "878043563283",
appId: "1:878043563283:web:c2a44f3c8b02ad8a17c6e6",
measurementId: "G-GMWQKL94ZD"
});
}
export const askForPermissionToReceiveNotifications = async () => {
try {
const messaging = getMessaging();
await messaging.requestPermission();
const token = await messaging.getToken();
console.log('Your token is:', token);
return token;
} catch (error) {
console.error(error);
}
}

Firebase initialization

I am using Firebase for the back-end of my app, my firebase configuration looks like :
const firebaseConfig = {
apiKey: 'xx',
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
}
firebase.initializeApp(firebaseConfig)
my question is what if i some configuration data is incorrect.
So how to check if my Firebase database is initialized correctly ? thanks
You can write a test case to check if your configuration is valid.
const getPost = async () => {
const snapshot = await firestore.collection('Posts').get();
const myPosts = snapshot.docs.map(collectIdsAndDocs);
console.log(myPosts);
setPosts({ myPosts });
};
const createPost = async (post) => {
const docRef = await firestore.collection('Posts').add(post);
const doc = await docRef.get();
console.log(doc);
};
createPost({ Title: 'My First Post', Content: 'My content' });
getPost();

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

Retrieve firebase data to web

// Initialize Firebase
var config = {
apiKey: "AIzaSyBz13eirmEOGD1uXOZwf6tKGnEsjfwsUFo",
authDomain: "platformtechproject.firebaseapp.com",
databaseURL: "https://platformtechproject.firebaseio.com",
projectId: "platformtechproject",
storageBucket: "platformtechproject.appspot.com",
messagingSenderId: "1065758005439"
};
firebase.initializeApp(config);
var database = firebase.database();
var msgRef = firebase.database().ref('survey');
//console.log(firebase);
var msgRef = firebase().ref('survey');
msgRef.on('value',gotData,errData);
I continue getting this error [Uncaught TypeError: firebase is not a function] as i am trying to read firebase data to web.
Chrome console error
here's how your code must be:
<script src="https://www.gstatic.com/firebasejs/4.8.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBz13eirmEOGD1uXOZwf6tKGnEsjfwsUFo",
authDomain: "platformtechproject.firebaseapp.com",
databaseURL: "https://platformtechproject.firebaseio.com",
projectId: "platformtechproject",
storageBucket: "platformtechproject.appspot.com",
messagingSenderId: "1065758005439"
};
firebase.initializeApp(config);
var database = firebase.database();
var msgRef = database.ref('survey');
msgRef.on("child_added",function(snapshot) {
var changedPost = snapshot.val();
console.log(changedPost)
});
</script>
The code above works as you expect:
Note that msgRef listens on these predefined "events".
Details here: Read Event Types
Regards
Change this:
var database = firebase.database();
var msgRef = firebase.database().ref('survey');
//console.log(firebase);
var msgRef = firebase().ref('survey');
msgRef.on('value',gotData,errData);
to this:
var database = firebase.database();
var msgRef = database.ref('survey');
msgRef.on('value', function(snapshot) {
//retrieve data
});

Categories