Get an unknown key name from Firebase function database trigger - javascript

I'm new to Firebase functions and trying to understand how to get a certain key from the database .onCreate trigger. Here is an example:
exports.createUserRoundData =
functions.database.ref('/data/players/{user_key}/').onCreate(event => {
var eventData = event.data.val();
var userKey = event.params.user_key;
var itemKey = eventData.items; // This returns an object
});
The structure is:
players > user_key > items > item_key > data
In the above scenario how can I retrieve the item_key?

Yes you can,
You need something like this :
exports.createUserRoundData = functions.database.ref('/data/players/{user_key}/').onCreate(event => {
var userKey = event.params.user_key; // Get user key parameter
var eventSnapshot = event.data; // Get player data
var itemsSnapshot = eventSnapshot.child('items'); // Get items data
itemsSnapshot.forEach(function(itemSnapshot) { // For each item
var itemKey = itemSnapshot.key; // Get item key
var itemData = itemSnapshot.val(); // Get item data
});
});
Here the Firebase Cloud Functions documentation.

Related

localStorage array.push

Could someone tell me how to push elements into an array in localStorage?
My code:
(localStorage.getItem('projects') === null) ? localStorage.setItem('projects', ['proj1', 'proj2', 'proj3']) : '';
var ItemGet = localStorage.getItem('projects');
function CreateObject() {
console.log(ItemGet);
var Serializable = JSON.parse(ItemGet);
Serializable.push('proj4');
console.log(ItemGet);
}
<button onclick="CreateObject()">Add Object</button>
General approach:
let old_data = JSON.parse(localStorage.getItem('projects'))
let new_data = old_data.push(some_new_data)
localStorage.setItem('projects',JSON.stringify(new_data))
I would do the following assuming that your data is not a multiDimensional array.
(localStorage.getItem('projects') === null) ? localStorage.setItem('projects',
JSON.stringify(['proj1', 'proj2', 'proj3'])) : '';
var ItemGet = localStorage.getItem('projects');
function CreateObject() {
var Serializable = JSON.parse(ItemGet);
Serializable.push('proj4');
localStorage.setItem('projects',JSON.stringify(Serializable));
}
The problem you are hitting is that data stored in localStorage has to be a string. You'll have to parse/stringify before settting/getting anything from local storage. If you didn't want to work with strings, you may find something like IndexedDB API
const stuff = [ 1, 2, 3 ];
// Stringify it before setting it
localStorage.setItem('stuff', JSON.stringify(stuff));
// Parse it after getting it
JSON.parse(localStorage.getItem('stuff'));
Here is an example of using IndexedDB API from the docs
const dbName = "the_name";
var request = indexedDB.open(dbName, 2);
request.onerror = function(event) {
// Handle errors.
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
// Create an objectStore to hold information about our customers. We're
// going to use "ssn" as our key path because it's guaranteed to be
// unique - or at least that's what I was told during the kickoff meeting.
var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
// Create an index to search customers by name. We may have duplicates
// so we can't use a unique index.
objectStore.createIndex("name", "name", { unique: false });
// Create an index to search customers by email. We want to ensure that
// no two customers have the same email, so use a unique index.
objectStore.createIndex("email", "email", { unique: true });
// Use transaction oncomplete to make sure the objectStore creation is
// finished before adding data into it.
objectStore.transaction.oncomplete = function(event) {
// Store values in the newly created objectStore.
var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers");
customerData.forEach(function(customer) {
customerObjectStore.add(customer);
});
};
};
There are also other solutions out there like PouchDB depending on your needs
Say for example you have an array. This is how you can store it in the local storage.
let my_array = [1, 2, 3, 4];
localStorage.setItem('local_val', JSON.stringify(my_array))
Now to push any data into the local storage array you have to override by the new data like bellow
let oldArray = JSON.parse(localStorage.getItem('local_val'))
oldArray.push(1000)
localStorage.setItem('local_val', JSON.stringify(oldArray))

Add items to basket and store in localStorage with JavaScript

I want to create an action for the button to be able to add items to the basket and keep data in localStorage. I'm struggling with push items when the basket has already more than one item inside. I can easily increase the quantity of existing items if an ID is same but can't add new items. Data I'm getting from JSON file. JSON contains only five unique IDs. Below part of my code.
AddBtn.addEventListener('click', function (add) { //Add item to when click AddBtn localStorage
add.preventDefault() // Avoid default action.
const basket = JSON.parse(localStorage.getItem('basket')); // Parse data from localstorage
let elementimageUrl = element.imageUrl; // element.imageUrl is a part of backend data received from JSON file
let elementId = element._id; // element._id is a part of backend data received from JSON file
let elementName = element.name; // element.name is a part of backend data received from JSON file
let elementPrice = element.price; // element.price is a part of backend data received from JSON file
let elementQuantity = 1;
if(basket === undefined || basket.length > 4 ){
//Existing data block in local storage
basket.forEach(product => {
if (product.elementId === elementId) {
product.elementQuantity++
console.log('increase');
}
});
} else{
//Non Exist data block in local storage
basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl}); // Push not existing data to localstorage
console.log('add')
window.location.reload();
}
localStorage.setItem('basket', JSON.stringify(basket));
});
Here is a working solution for your problem.
AddBtn.addEventListener('click', function (add) { //Add item to when click AddBtn localStorage
add.preventDefault() // Avoid default action.
let basket = JSON.parse(localStorage.getItem('basket')); // Parse data from localstorage
let elementimageUrl = element.imageUrl; // element.imageUrl is a part of backend data received from JSON file
let elementId = element._id; // element._id is a part of backend data received from JSON file
let elementName = element.name; // element.name is a part of backend data received from JSON file
let elementPrice = element.price; // element.price is a part of backend data received from JSON file
let elementQuantity = 1;
if (!basket) {
basket = [];
}
// find the index of the item if already in basket
const itemIndexInBasket = basket.findIndex(basketEntry => basketEntry.elementId === elementId);
if (itemIndexInBasket !== -1) {
basket[itemIndexInBasket].elementQuantity++;
} else {
basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl}); // Push not existing data to localstorage
}
localStorage.setItem('basket', JSON.stringify(basket));
});
Can you share a jsfiddle link with dummy values for variables? It will be a lot easier to debug.
Seeing the above explanation that you are facing a problem with push items I assumed this below data and it is working.
const basket = [{abc:"1"},{abcs:'3'}];
let elementimageUrl = 'abc';
let elementId = 1;
let elementName = 'a';
let elementPrice = 10;
let elementQuantity = 1;
basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl});
console.log('add')
console.log(basket);
localStorage.setItem('basket', JSON.stringify(basket));

Trying to delete the value of key for web application through firebase

what would make this work so that when the user types the correct tobedeleted value, the database deletes corresponding key with entered name?
function remove(){
var nameInput=document.getElementById("nameInput");
var database = firebase.database();
var tobedeleted = document.getElementById("tobedeleted").value;
var rootRef = database.ref("information");
var query = rootRef.orderByKey();
//gets generated keys
query.once("value",function(snapshot){
snapshot.forEach(function(childSnapshot){
var key = childSnapshot.key;
var val = childSnapshot.val();
console.log(val.name);
console.log(tobedeleted);
if (val.name===tobedeleted /*edited from val.name.equalTo(tobedeleted)*/)
{
rootRef.child("information/"+key).remove();
}
});
});
Found the solution: just changed ("information/"+key) to (key)

Fetching data from firebase web

I am trying to fetch the data for website using java script.
Problem I am getting is that I am unable to get the key of
Users-->Customers-->Key-->(name, phone).
I am unable to find a syntax of it
Code I am trying is
var fireheading = document.getElementById("fireHeading");
var firebaseHeadingRef = firebase.database().ref().child("Users").child("Customers").child(uid).child("name");
firebaseHeadingRef.on('value', function(datasnapShot){
fireHeading.innerText = datasnapShot.val();
});
To get data from Firebase in javascript, you would do this:
var fireHeading = document.getElementById("fireHeading");
// "key" is the customer key
var ref = firebase.database().ref("Users/Customers/" + key);
ref.once("value", function(snapshot){
// Contains all data from Firebase
var data = snapshot.val();
// Has customer name
var customerName = data.Name;
// Has customer phone
var customerPhone = data.Phone;
// Append data to view
fireHeading.innerText = customerName;
});
This should work.

Retrieve Keys and elements of Array Firebase Database

I'm working with Firebase realtime database and I want to retrieve an array data:
Data:
And my function:
function traerUsuarios(firebase)
{
var ref = firebase.database().ref().child('/Usuario');
console.log(ref)
ref.once('value', function (snap) {
snap.forEach(function (item) {
var itemVal = item.val();
console.log(itemVal);
});
});
}
But the result:
Show me object but no de for of the items
What im doing wrong?
Each item in your for loop are the children of Usario. Each of these children (from your picture 056BN.., CQL.., and E4ll) have an object as their value (hence why they have a + next to them in the database).
So when you say item.val() you're getting the value of each one of those children, which is their corresponding object (The data you see when you click the + in the database.
Thanks to #MarksCode , I fixed the function with data refs:
function traerUsuarios(firebase) { var key;
var starCountRef;
var usuarios=new Array();
// var ref = firebase.database().ref().child('/Usuario');
var query = firebase.database().ref("/Usuario").orderByKey();
query.once("value")
.then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
// key will be "ada" the first time and "alan" the second time
key = childSnapshot.key;
starCountRef = firebase.database().ref("/Usuario/"+key);
starCountRef.on('value', function (snapshot) {
console.log(snapshot.val());
usuarios.push([key,snapshot.val()]);
});
});
}); }
And the result show me the values:

Categories