How to update multiple fields in Firebase Web? - javascript

I have the following code where I want to update some simple values in my Firebase database using the JavaScript, Web SDK.
However, it doesn't run/update my database. What's wrong here?
var dbRef = firebase.database().ref().child('feeds').child(selectedFeed).child('audio');
var uid = dbRef.push().key;
var data = {
"downloadURL": uploadTask.snapshot.downloadURL,
"fileName": file.name,
"timeStamp": selectedDateUnix
};
var updates = {};
updates["mostRecentKey"] = uid;
updates[uid] = data;
dbRef.update(updates).then(function(){
//success
alert("Successfully Uploaded. This is now available to be listened to by your users.");
}).catch(function(error){
//failure
alert(error.message);
});

While it doesn't ever specify in the Firebase docs and actually I felt indicated it wasn't required; You MUST cast your data. For example:
This does not work. Directly accessing the variable.
var myNum = 10;
var data = {};
data["myNum"] = myNum;
This does work, but doesn't allow a dynamic use of a var.
var data = {};
data["myNum"] = 10;
Finally, this works and was my solution using a variable reference. Cast your data.
var myNum = 10;
var data = {};
data["myNum"] = Number(myNum);

Related

Put variable name in JSON Array (fetched by an api)

I am very new to Javascript but I will try to put this in convenient way. I am having this api where I am fetching the rank of a crypto (Ripple; currently ranked 7 and is subject to change overtime ), code below:
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
}
Now this is another function for an api where I extract other infos (having 5000+ crytos listed, including ripple)
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRP = data[7].symbol;
// Here instead of [7], I need to put the value extracted from XRPrank above so that whenever the rank is changed I get the latest value on data.[].
If someone could please advise.
In JavaScript there are several ways to achieve what you are looking for. The following is an adaptation of your current code with what I think are the minimal changes that you have to do, 1. use return followed by XRPrank 2. Call myFunction from myXRP and replace the data index by XRPrank.
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
return XRPrank; // add this
}
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRPrank = myFunction(); // add this
// var XRP = data[7].symbol; instead of this
var XRP = data[XRPrank].symbol; // use this
}
Resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

How to display data from localstorage using handlebars?

In my program i fetch data from console and store it in localstorage and webSQL . Now i want to display the stored data from localstorage using handlebar. I used the following code:
console.log(response); // To get data from console
var offer = JSON.stringify(response);
localStorage.setItem("object",offer); // saved in localstorage
var seasons= localStorage.getItem("object"); // get data from localstorage and saved in variable seasons
var mysource = document.getElementById("detailstemplate").innerHTML;
var mytemplate = Handlebars.compile(mysource);
var myresult = mytemplate(seasons);
document.getElementById("divOffers").innerHTML = myresult;
I used the last 4 lines to display data using handlebars. But it is not working. Please correct the error.Can anyone help with this?
var season = localStorage.getItem("cart");
var season2 = $.parseJSON(season);
var mytemp = $("#mainmenu-template").html(); // Grab the template script
var ourtemp = Handlebars.compile(mytemp); // Compile the template
var resultnew = ourtemp(season2);
$("#divMainMenu").append(resultnew);

Retrieve information from firebase doesn't work, key is not a function

I tried to solve it like this:
How to pull out data from firebase into html page - Stackoverflow
But I couldn't get it to work.
My html looks where I'll put the information from Firebase looks this in javascript:
var createTable = "<table><thead><tr id='keysRow'></tr></thead>";
var endHead = "<tbody><tr id='valuesRow'></tr></tbody></table>";
//More code that's connecting to each other and displays it in a div.
//F12 is showing me that this works.
Firebase.js:
var firebase = require('firebase');
firebase.initializeApp(config);
var v = firebase.database();
var users = firebase.database().ref("users");
users.orderByKey().once('child_added', function(snapshot){
snapshot.forEach(function(childsnapshot){
var key = childsnapshot.key(); <---------error
var data = childsnapshot.val();
$('#keysRow').append('<th>' + key + '</th>');
$('#valuesRow').append('<td>' + data + '</td>');
});
});
config is just the link to the firebase. I have no problem using the config to write in the firebase.
The error is telling me: "childsnapshot.key is not a function"
Also my firebase has 10 different values I need to get.
Change this:
var key = childsnapshot.key();
to this:
var key = childsnapshot.key;
check this link to see what has changed in Firebase 3.x: https://firebase.google.com/support/guides/firebase-web

Why is db.transaction not working with indexeddb?

I am new at using inxededdb and am trying to get data out of a store. The store contains data, but for some reason the code stops after trying to set the var tx. If I am missing anything please let me know. Here is the function with which I am trying to get the book:
function getBook(){
var tx = db.transaction("book", "readonly");
var store = tx.objectStore("book");
var index = store.index("by_getid");
var request = index.get("<?php echo $_GET['book'] ?>");
request.onsuccess = function() {
var matching = request.result;
if (matching !== undefined) {
document.getElementById("text-container").innerHTML = matching.text;
} else {
alert('no match');
report(null);
}
};
}
Solved Version:
function getBook(){
var db;
var request = indexedDB.open("library", 1);
request.onsuccess = function (evt) {
db = request.result;
var transaction = db.transaction(["book"]);
var objectStore = transaction.objectStore("book");
var requesttrans = objectStore.get(<?php echo $_GET['book'] ?>);
requesttrans.onerror = function(event) {
};
requesttrans.onsuccess = function(event) {
alert(requesttrans.result.text);
};
};
}
The problem is probably your db variable. You are probably accessing a closed or null instance of a connection object.
Try instead to create the db connection right inside the function. Do NOT use a global db variable.
index.get yields primary key. You have to get record value using the resulting primary key.
I has problem with transaction, it's return error db.transaction is not a function or return undefined.
You will try like this, it's working for me:
const table = transaction.objectStore('list');
const query = table.getAll();
query.onsuccess = () => {
const list = query?.result;
console.log(list);
};

Error "A mutation operation was attempted on a database that did not allow mutations." when retrieving data in indexedDB

I have this simple example code:
var request = mozIndexedDB.open('MyTestDatabase');
request.onsuccess = function(event){
var db = event.target.result;
var request = db.setVersion('1.0');
request.onsuccess = function(event){
console.log("Success version.");
if(!db.objectStoreNames.contains('customers')){
console.log("Creating objectStore");
db.createObjectStore('customers', {keyPath: 'ssn'});
}
var transaction = db.transaction([], IDBTransaction.READ_WRITE, 2000);
transaction.oncomplete = function(){
console.log("Success transaction");
var objectStore = transaction.objectStore('customers');
};
};
};
I am getting this:
A mutation operation was attempted on a database that did not allow mutations." code: "6
on line
var objectStore = transaction.objectStore('customers');
Can't figure out - what do I do wrong?
You can create or delete an object store only in a versionchange transaction
see: https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase
I think I found the answer. I shouldn't access objectStore inside oncomplete. I just need to do it after making new transaction. Right way is this:
var transaction = db.transaction([], IDBTransaction.READ_WRITE, 2000);
transaction.oncomplete = function(){
console.log("Success transaction");
};
var objectStore = transaction.objectStore('customers');
Btw, this is how exactly Mozilla's MDN shows. https://developer.mozilla.org/en/IndexedDB/Using_IndexedDB#section_10
I didn't try that code but judging by the documentation you shouldn't pass an empty list as first parameter to db.transaction() - it should rather be db.transaction(["customers"], ...) because you want to work with that object store.

Categories

Resources