How to read data from firebase and write it in textboxs javascript - javascript

I am reading a lot of different data from my firebase database, currently, I have hard coded it. This works fine, however I have soo many lines of code that now when I want to alter my code it gets really confusing. Below I have pasted the current apporach I have taken.
var ref = new Firebase("URL");
// Data set 1
ref.on('child_added', function(snapshot) {
var snapshot = snapshot.val();
textbox1.innerHTML = snapshot.getvalue1.age;
});
ref.on('child_changed', function(snapshot) {
var snapshot = snapshot.val();
textbox1.innerHTML = snapshot.getvalue1.age;
});
// Data set 2
ref.on('child_added', function(snapshot) {
var snapshot = snapshot.val();
textbox2.innerHTML = snapshot.getvalue2.age;
});
ref.on('child_changed', function(snapshot) {
var snapshot = snapshot.val();
textbox2.innerHTML = snapshot.getvalue2.age;
});
.....
.....
.....
// Data set 100
ref.on('child_added', function(snapshot) {
var snapshot = snapshot.val();
textbox100.innerHTML = snapshot.getvalue100.age;
});
ref.on('child_changed', function(snapshot) {
var snapshot = snapshot.val();
textbox100.innerHTML = snapshot.getvalue100.age;
});
Instead of the approach I have taken, is it possible to use a for loop or something like that to loop through each data because my structure for each textbox / keyword in firebase is more or less the same.
I am fairly new to javascript but from my knowledge of java, I believe it would be started of something like this;
var myTextbox = document.getElementById("mytextbox");
for (var i = 0; i < myTextbox.length; i++) {
}
Any help is welcomed, if my question is not clear please let me know.
EDITED:
Mydata:
textbox1 - value - age : "This is textbox 1, age:21"
textbox2 - value - age : "This is textbox 2, age:53"
textbox2 - value - age : "This is textbox 3, age:04"
....
....

I am not an expert on firebase but here are some potential solutions you can try. For example, instead of writing a child_added and child_changed, you can use 'value'. (Reference)
ref.on('value', function(snapshot) {
var snapshot = snapshot.val();
textbox1.innerHTML = snapshot.getvalue1.age;
});
But this is not a good solution for your problem as you want all the values retrieved at once.
It seems your snapshot has all the values with attributes'getValuei' where i is from 1...n.
A better solution could be something like this..
ref.on('value', function(snapshot) {
var snapshot = snapshot.val();
textbox1.innerHTML = snapshot.getvalue1.age;
textbox2.innerHTML = snapshot.getvalue2.age;
textbox3.innerHTML = snapshot.getvalue3.age; //..and so on..
});

Related

Prevent duplicate action when multiple storage keys are modified

I've been learning JavaScript for about a month now, and right now I’m working on a little project (Shopping Cart) to dive into storage events. I’ve successfully managed to store a few keys from “tab1” into the local storage and retrieve them from “tab2”. However, I came across a particular “problem”, which I’ve been struggling with for the last couple of days.
On “tab1” I have five keys that are being stored in localStorage. on “tab2” I need to complete an action (create an HTML element) every time the localStorage changes. The problem is that the action is being triggered once for every key that’s changed. In other words, I keep getting 5 duplicate HTML elements.
I’ve spent many hours searching for answers on forums, YouTube videos, blogs and of course here. So far no luck. I’ve also been reading the documentation on localStorage, but since I’m new at this, it’s not very clear for me.
I hope you can help find a solution or understand why I keep getting these duplicate actions.
This is an example of the code I have so far:
let itemList = document.getElementById("itemList");
let summaryItem = document.getElementById("summaryItem_01");
let summaryImage = document.getElementById("itemImage_01");
let summaryName = document.getElementById("item_Name_01");
let summaryModel = document.getElementById("itemModel_01");
let summaryQuantity = document.getElementById("detailQuantityDisplay_01");
let summaryPrice = document.getElementById("itemPriceAmount_01");
//Gets localStorage info on page load and feeds summaryItem fields.
window.addEventListener("load", () => {
let itemImage = localStorage.getItem("modalItemImage");
let itemName = localStorage.getItem("modalItemName");
let itemModel = localStorage.getItem("modalItemModel");
let itemQuantity = localStorage.getItem("modalItemQuantity");
let itemPrice = localStorage.getItem("modalItemUnitPrice");
//Prints localStorage info to summaryItem element.
summaryImage.setAttribute("src", itemImage);
summaryName.innerText = itemName;
summaryModel.innerText = itemModel;
summaryQuantity.value = itemQuantity;
summaryPrice.innerText = itemPrice;
});
//This is where I'm getting the duplicate action
window.addEventListener("storage", () => {
let a = document.createElement("article");
itemList.appendChild(a);
});
UPDATE:
After MauriceNino's suggestion, I ended up with this code and it worked perfectly:
//Tab1
let modalItem = {
modalItemImage: displayModalImage.innerHTML.slice(10, -2),
modalItemName: displayModalName.innerText,
modalItemModel: displayModalModel.innerText,
modalItemQuantity: displayModalQty.value,
modalItemUnitPrice: displayModalPrice.innerText,
modalItemTotal: displayModalTotal.innerText,
};
localStorage.setItem("modalItem", JSON.stringify(modalItem));
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Tab2
//Gets localStorage info from modal
let data = JSON.parse(localStorage.getItem("modalItem"));
let dataArray = Object.values(data);
let itemImage = dataArray[0];
let itemName = dataArray[1];
let itemModel = dataArray[2];
let itemQuantity = dataArray[3];
let itemPrice = dataArray[4];
//Prints localStorage info to summaryItem element.
summaryImage.setAttribute("src", itemImage);
summaryName.innerText = itemName;
summaryModel.innerText = itemModel;
summaryQuantity.value = itemQuantity;
summaryPrice.innerText = itemPrice;
//Creates new summaryItem when there's a chnage on localStorage.
window.addEventListener("storage", () => {
let a = document.createElement("article");
itemList.appendChild(a);
});
You could just save it as one element like so:
//Gets localStorage info on page load and feeds summaryItem fields.
window.addEventListener("load", () => {
// Get all the data in a single statement
let { itemImage, itemName, itemModel, itemQuantity, itemPrice }
= localStorage.getItem("modalItem");
//Prints localStorage info to summaryItem element.
summaryImage.setAttribute("src", itemImage);
// ...
});
//Will be called only once now
window.addEventListener("storage", () => {
let a = document.createElement("article");
itemList.appendChild(a);
});
// This is where you are saving your localStorage settings
localStorage.setItem("modalItem", {
itemImage: 'image',
itemName: 'name',
itemModel: 'model',
itemQuantity: 2,
itemPrice: 3
});

Need help on calling datas from firebase html

Firebase example:
Users:
User1
A
123
234
345
B
C
Above is the firebase data.
I wanted to call all the data under User1, A. Which means "123", "234", "345" should be the output for my table. I also wanted to display them to be displayed in a table I have in my html file using javascript. Can anyone advise? I am new to firebase and am confused with the other guides online.
Should I create a table using javascript or keep my table at html file?
Thank you for advise and help.
For Real Time Database try this:
firebase.database().ref('/User1/A').once('value').then(function(snapshot) {
let items = snapshot.val();
items.forEach( (v) => writeData(v) );
});
const writeData = (value) => {
let el = document.querySelector('p');
el.innerHTML = value;
document.appendChild(el);
}
By doing the following, in JavaScript you will get all the children of the User1/A node:
var ref = firebase.database().ref('User1/A');
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
console.log(childKey);
var childData = childSnapshot.val();
console.log(childData);
//....
});
});
From there you can populate your HTML table

Saving array of data to Firebase with Javascript/NodeJs

I need to save data to the database but at a certain index. I tried pulling the data down with
var people = [];
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var ID = childSnapshot.key;
childSnapshot.forEach(function(lastSnapshot) {
var qr = lastSnapshot.val();
people.push({[ID]: qr});
return true;
});
});
My firebase structure:
people: {
jake: "231",
jessica: "412",
rachel: "112"
}
Then I splice the list and add someone at a certain index:
index = 1; // add person after jessica
people.splice(index, 0, person);
I want to sync this back up to Firebase but set and update don't allow a format like this.
How can I do this? Thanks!

I only got database output once, but not again. Why wont this work?

I am working in firebase for a web app. The first time I did the query it worked, then I added the second reference and it broke. Upon doing that, I rolled back to when it previously worked and it no longer worked either. I am getting no errors in the console.
function displayMessage(){
var messageId;
alert("Firebase Initializing UserID: " + Parse.User.current().id);
var reference = new Firebase("https://gibber.firebaseio.com/Recent");
reference.orderByChild("userId").equalTo(Parse.User.current().id).on("child_added", function(snapshot) {
alert(snapshot.key());
messageId = snapshot.key();
});
var reference2 = new Firebase("https://gibber.firebaseio.com/Recent");
reference2.child(messageId+"/lastMessage").on("value", function(snapshot) {
alert(snapshot.val());///snapshot should be last message
});
};
The nesting of you code is off, which is hard to spot because the indentation is messy.
This works:
var userId = 'sKdkC6sGYb';
var ref = new Firebase("https://gibber.firebaseio.com/Recent");
ref.orderByChild("userId").equalTo(userId).on("child_added", function(snapshot) {
console.log('child_added: '+snapshot.key());
var messageId = snapshot.key();
ref.child(messageId+"/lastMessage").on("value", function(othersnapshot) {
console.log('value: '+othersnapshot.val());///snapshot should be last message
});
});
I'm not sure why you're taking this two-queried approach though, the lastMessage property is available in the outer snapshot already:
var userId = 'sKdkC6sGYb';
var ref = new Firebase("https://gibber.firebaseio.com/Recent");
ref.orderByChild("userId").equalTo(userId).on("child_added", function(snapshot) {
console.log('child_added: '+snapshot.key());
console.log('value: '+snapshot.val().lastMessage);
});
See: http://jsbin.com/bikoni/edit?js,console

Node/Javascript only send changed values

I'm writing a simple application where I send values to a mqtt broker given by a pot-meter (variable resistor). The thing I am trying to accomplish is that I only send changed values to save bandwidth. I am trying Object.observe, but that does not do anything. Can anybody help me?
My code:
var analogValue = 0;
every((0.5).second(), function() {
analogValue = my.sensor.analogRead();
var values = {values:[{key:'resistance', value: analogValue}]}
//another experiment here
var arr = ['resitance', analogValue];
Array.observe(arr, function(changes) {
console.log(changes);
});
arr[1] = analogValue
console.log('sent ',values,'to ',thingTopic)
client.publish(thingTopic, JSON.stringify(values));
});
var o = [analogValue];
Object.observe(o, function (changes) {
console.log(changes);
//eventually publish only changes to broker here
})
o.name = [analogValue]
You don't need to use Object.observe. You can just save the last measurement and check the new one against it. Like this:
// I'm assuming that any actual measurement will be different than 0
var lastMeasurement = 0;
every((0.5).second(), function() {
var analogValue = my.sensor.analogRead();
if (lastMeasurement !== analogValue) {
// the new value is different
var values = {values:[{key:'resistance', value: analogValue}]};
client.publish(thingTopic, JSON.stringify(values));
// update the last measurement value
lastMeasurement = analogValue;
}
});

Categories