I have the following code I'm trying to make a simple hit counter with. However, it doesn't work when I run it locally. When I start newHits as blank, it throws the error: Uncaught Error: Reference.set failed: First argument contains undefined in property 'hits.number'.
When I start it at 1, it just doesn't change the value of the hits in the database. Any help is appreciated: I'm new to programming. Thanks so much!
$(document).ready(function(){
var database = firebase.database();
var hits;
var newHits = 1;
var hitsRef = firebase.database().ref('hits');
hitsRef.once('value', function(snapshot){
console.log("hitsRef.once called");
hits = snapshot.val().number;
console.log("hits: "+hits);
newHits = hits+1;
console.log(newHits);
});
hitsRef.set({
number: newHits
});
});
the simple way to do that by using transaction see here
$(document).ready(function(){
var database = firebase.database();
var hitsRef = firebase.database().ref('hits/number');
hitsRef.transaction(function(hits){
console.log("hitsRef.once called");
hits++;
return hits
});
}
This is due to async nature of once(). According to your code, both once() and set() are called for the same value of i at once.
If you want to test it, place your set() within a setTimeout() like,
setTimeout(function(){
hitsRef.set({
number: newHits
});
}, 2000);
You will see that your problem is solved but this is not the correct way.Try this instead,
var i = 1;
hitsRef.once('value', function(snapshot){
console.log("hitsRef.once called");
hits = snapshot.val().number;
console.log("hits: "+hits);
newHits = hits+1;
console.log(newHits);
})
.then( function() { // change starts here
hitsRef.set({
number: newHits
});
});
Your set() method will only be called when once() is done retrieving hits. This works because once() returns a promise and it is thenable.
Read these then() in javascript and promises.
Related
I am trying to update an entry in my simple to do app with indexedDB, however I am getting Failed to execute 'put' on 'IDBObjectStore': The transaction has finished.
I can't seem to figure out why it won't finish the transaction, I tried the debugger and it stops at this line: var updateNameRequest = tasksStore.put( requestForItem.result.name, Number(requestForItem.result.id)) Please see the snippet I included below. For additional context creating, reading, and deleting work just fine it's just updating data that I'm having trouble with
I also tried to implement the openCursor technique which I got from Mozilla which I commented out since it also doesn't work (I get the same behavior) Check out my repo I know it's still very messy :(
const request = window.indexedDB.open("toDoList", 2);
var db;
request.onsuccess = function (event) {
console.log("check out some data about our opened db: ", request.result);
db = event.target.result; // result of opening the indexedDB instance "toDoList"
getTasks(); //just a function to retrieve data
};
$(document).on("click", ".editBtn", function () {
var transaction = db.transaction("tasks", "readwrite");
var tasksStore = transaction.objectStore("tasks");
console.log(tasksStore);
let taskId = $(this).attr("idNo");
var requestForItem = tasksStore.get(Number(taskId));
requestForItem.onsuccess = function () {
// console.log(requestForItem.result)
var oldData = requestForItem.result;
// prepopulate the input
$(".editInput").val(requestForItem.result.name);
$(".saveBtn").click(function () {
requestForItem.result.name = $(".editInput").val().trim()
console.log( requestForItem.result)
var updateNameRequest = tasksStore.put( requestForItem.result.name, Number(requestForItem.result.id))
console.log("-------------", updateNameRequest.transaction) // doesn't get to this line
updateNameRequest.onerror = function() {
console.log("something went wrong")
console.log(updateNameRequest.error)
};
updateNameRequest.onsuccess = function() {
console.log("here")
$(".editInput").val("")
getTasks();
};
});
};
Indexed DB transactions auto-commit when all requests have been completed and no further requests were made before control returns to the event loop. Put another way - you can make new requests in the success or error callback from a previous request, but not in other asynchronous callbacks such as event handlers.
You need to start a new transaction within the click handler, because any previous transaction will have autocommitted.
I have the following problem: I want to get data from a specific node from firebase during runtime. It should display "stats" of a player that was selected before. Now I could use on() to get all the data in the beginning, but I want to save data transfers by only downloading the data of on player if I need to, so I tried to use once like this:
var firebaseRef = firebase.database().ref();
function getScoresOfPlayer(player) {
console.log(player);
var selectedPlayerScores = [];
firebaseRef.once('value').then(function(snap) {
snap.child('scores').child('thierschi').forEach(function(child) {
selectedPlayerScores.push([child.key, child.val()]);
});
});
return selectedPlayerScores;
}
The problem is that it retruns the array before the data was loaded into it. Also I checked the docs and didn't find a better solution.
Thanks in advance!
This is because the getScoresOfPlayer function returns selectedPlayerScores before the promise returned by the once() method resolves.
You should include the return within the then(), as follows:
var firebaseRef = firebase.database().ref();
function getScoresOfPlayer(player) {
console.log(player);
var selectedPlayerScores = [];
return firebaseRef.once('value') //return here as well
.then(function(snap) {
snap.child('scores').child(player).forEach(function(child) { //I guess it should be child(player) and not child('thierschi') here
selectedPlayerScores.push([child.key, child.val()]);
});
return selectedPlayerScores;
});
}
which means that you have to call your function as follows, since it is going to be asynchronous and to return a promise:
getScoresOfPlayer('xyz')
.then(function(selectedPlayerScores) {
....
})
Again, i got some question on indexeddb. I´m getting a
InvalidStateError: A Mutation operation was attempted on a database
that did not allow mutations.
and also an
AbortError
Here is my code:
DB_LINK.prototype.pushStoreNumeric = function ()
{
// Saving Values
var _temp = 0;
var _version = this.link.version;
var _name = this.link.name;
var that = this;
var _objectStoreNames = this.link.objectStoreNames;
// Close DB
this.link.close();
this.state = 4;
// Reopen Database
this.req = indexedDB.open(_name,_version+1); // Abort error here
this.req.onupgradeneeded = function () {
that.state = 1;
// Get Number of object stores
_temp = _objectStoreNames.length;
if(_temp != 0)
{
// Already object stores: read highest value
_temp = parseInt(_objectStoreNames[_objectStoreNames.length - 1]);
}
that.link.createObjectStore(_temp); // InvalidStateError here
};
I have marked per comment where the errors occur.
The InvalidStateError occures first, the AbortError follows.
I am calling this function inside another onsuccess function of the same database. Might this be the problem?
What is this.link? That's probably the problem. You need to be doing createObjectStore on the database instance created by the indexedDB.open request. So either this.req.result.createObjectStore or (if you change to this.req.onupgradeneeded = function (e) {) you could use e.target.result.createObjectStore.
More generally, I can't really comment on what your code is supposed to be doing because I can only see a snippet, but it looks really weird how you are incrementing the version every time this is called. Probably you don't actually want to be doing that. You might want to read a bit more documentation.
First of all, I'm using JQuery. Take a look:
$(document).ready(function() {
var btcusd = 600;
function getRate() {
$.get("rate.php", function(data) {
var btcArr = JSON.parse(data, true);
btcusd = btcArr["last"];
//This will give me the correct value
console.log(btcusd);
});
}
setInterval(function() {
//This will say 600 every time
console.log(btcusd);
//Update rate for next loop
getRate();
}, 3000);
});
Chrome console gives me the 600 every 3 seconds. If I do this manually in the chrome live console, I will get a real value, like 595.32.
Why does this not work like intended?
Thanks for help.
I think #Tobbe is quite on point here. One thing you can do to confirm, is to add something like console.log( btcArr ) and that should show you whether you're getting anything back.
I set up a not too different demo that should that once the ajax callback successfully updates the value, it never goes back to 600, showing that indeed the value does get changed in the callback and the new value is available outside the ajax callback.
The ajax code I used is:
function getRate() {
var gafa = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=100&q=";
var url = gafa + encodeURI('http://news.yahoo.com/rss/sports/')+"&callback=?";
$.getJSON(url, function(data) {
//var btcArr = JSON.parse(data, true);
var xData = data.responseData.feed.entries
//btcusd = btcArr["last"];
btcusd = xData.length;;
//This will give me the correct value
console.log(btcusd);
});
}
The rest of the code is yours: WORKING JSFIDDLE DEMO
Has anyone found that their javascript doesnt work, but when they step through the code it works fine ?
var cookie = getCookie('lusr');
var username = cookie;
if(!cookie){
$("#UserNav").load("loginform.html");
$("#loginbtn").click( function(){
var username = $("#usernametxt").val();
var password = $("#passwordtxt").val();
login(username,password);
});
}else{
$("#UserNav").load("user.htm");
$("#WelcomeUser").text("Welcome "+ username);
}
My issue occurs on this line :
$("#WelcomeUser").text("Welcome "+ username);
That's because load() is asynchronous: it returns right away, performs its work in the background, then calls a user-provided function when its task is complete. The stepping delay gives you the illusion that the function is synchronous and performs all its work before returning.
Therefore, you should pass a callback function to load() and perform your subsequent work inside that callback:
var cookie = getCookie("lusr");
if(!cookie) {
$("#UserNav").load("loginform.html", function() {
$("#loginbtn").click(function() {
var username = $("#usernametxt").val();
var password = $("#passwordtxt").val();
login(username, password);
});
});
} else {
$("#UserNav").load("user.htm", function() {
$("#WelcomeUser").text("Welcome " + cookie);
});
}
You are using the load() function which asynchronously fetches from the server. This means your form has not loaded by the time you go searching for its fields.
The reason it works when you step through is because it gives it time to load the form while you step.
You can use another version of load which has an asynchonous callback function, allowing you to provide functionality only to be called once the load is complete.
Check the jQuery docs for more info.