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!
Related
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))
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
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.
I have Firebase database managing following structure.
-DATA
-New
-CONTENTS
-animals_animal1: 1
-foods_food10: 4
-foods_food6: 5
-girls_girl1: 2
-girls_girl5: 3
I want to get children's value by using orderByValue() as 1,2,3,4,5 manner using snaps.forEach in JavaScript. My code as follows.
exports.handleAddNewContentAndAddToNewEvent = functions.database.ref('/CONTENT_MANAGEMENT/DATA/CONTENTS/{contentId}')
.onWrite(event => {
// Only edit data when it is first created.
if (event.data.previous.exists()) {
return;
}
// Exit when the data is deleted.
if (!event.data.exists()) {
return;
}
var newContentsRef = event.data.ref.parent.parent.child('PACKS/New/CONTENTS');
return Promise.all([
newContentsRef.orderByValue().once('value')
]).then(function(snaps) {
snaps.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
console.log('loaded', childKey);
// ...
});
});
});
However, I failed to get intended solution. How to get solution what I need?
Structure
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..
});