Adding to existing Firebase integer - javascript

Is it possible to add to an existing integer stored in firebase. I am building an application that keeps track of a users word count by storing a key in their userId firebase key called wordCount:. I'm able to successfully update that key when the user clicks a button called "marked as read" but unfortunately it just replaces the integer instead of adding to it. Is it possible to get it to add to the value of the key wordCount: rather than replacing it.
Here is the code inside one of my controllers. Side note, angularAuth.getAuth just checks to see if the user is logged in or not
this.markedAsRead = function(wordCount){
if(angularAuth.getAuth){
var userBase = new Firebase('https://readyread.firebaseio.com/users/'+angularAuth.getAuth.uid)
userBase.update({
wordsRead: wordCount
})
}else{
console.log('please log in to use this feature')
} }

I was able to get it thanks to an idea of #manube
this.markedAsRead = function(words){
var userBase = $firebaseObject(new Firebase('https://readyread.firebaseio.com/users/'+angularAuth.getAuth.uid))
var users = new Firebase('https://readyread.firebaseio.com/users/'+angularAuth.getAuth.uid)
userBase.$loaded().then(function(data){
self.count = data.wordsRead
users.update({
wordsRead: self.count+words
})
})}

Related

Storing and Retrieving User Input

How to store user input from multiple pages and retrieve/display back user data on another html page
I am making a voting system and I needed help storing my results. Currently using local storage in JavaScript. Please do not recommended using data base as the deadline for the project is in 4 days.
So the main problem is whenever a user enters his/her preferences for a candidate the preferences are directly stored on another html page, but as soon as the second user enters his/her preferences the preferences by the first candidate disappears and the preferences for the second candidate gets stored.
I need to store preferences from every user to the html page. I need a efficient way to store my results in.
My local storage code
//store//
localStorage.setItem("preference1", selection[i].value);
// retrieve //
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
document.getElementById('display').innerHTML += `${key}: ${value} <br>`;
}
This answer is covering how you can add multiple "sets" of data to local storage (it is not secure and only works for a single browser):
Build an object containing all of the preferences for the current user
Push these into an array that will be stored in local storage
When saving the array, use JSON.stringify to convert the array to a string
When retrieving the array (as a string), convert it back using JSON.parse
(As localstorage is not allowed inside stack snippets, check this identical JSFiddle to see it working)
// Keeping your key in a variable is generally good practice
// so it's easy to change and immune to typos
const localStorageKey = 'preferences'
function addNew() {
// Build an object containing all the prefernces for the current user
var preferences = {
a: 'A',
b: 'B',
c: 'C',
}
// Load the existing data
var existingData = load()
// Push the new users data to the data
existingData.push(preferences)
// Save the data
save(existingData)
}
function load() {
// Get the saved data from local storage
var existing = localStorage.getItem(localStorageKey)
if (existing) {
// If the data exists, parse it back into an array
existing = JSON.parse(existing)
} else {
// If this is the first time, create an empty array
existing = []
}
// Return the array with any previous data included
return existing
}
function save(data) {
// Save data to local storage, converting the JS array to a string first
localStorage.setItem(localStorageKey, JSON.stringify(data))
}
// Adding events to the example buttons
document.getElementById("example1").onclick = addNew
document.getElementById("example2").onclick = function() {
var currentSave = load()
console.log(currentSave)
}
<button id="example1">Add new users data</button>
<button id="example2">Print out currently saved data</button>

How to fix 'Array.push is not a function' error in Javascript

Im trying to create a small database with localstorage for a small project ( just to emulate a login ).
It's supposed to open two prompts to ask username and password and then store it in a Array of Objects. What happens is that I iniciate the first element of the Array with an Object of an admin and when after inserting the second user (it lets me add one more after the admin) it says that the Users(Array).push is not a function.
var name = prompt('Insert your name');
var password = prompt('Insert your password');
if(localStorage.length!==0){
Users=localStorage.getItem('Users');
}else {
var Users = [{
name:'admin',
password:'admin'
}];
}
var person = {
name:name,
password:password
}
Users.push(person);
localStorage.setItem('Users',Users);
Its supposed to store users and passwords as object inside the array as I load the page over and over again.
Thank you in advance for anyone willing to help
localStorage stores key/value pairs, but the value is stored as strings, not other data structures.
localStorage.setItem('Users', JSON.stringify(Users));
and then when you get it:
Users = JSON.parse(localStorage.getItem('Users'));
You are having an error because when you get it from localStorage it's not an Array.

Querying firebase database to retrieve user name

I am working on firebase for the first time. I am confused in querying the database. I have two objects on the database, one is the Auth and second one is the Chats. In Auths I have number of UID(user id) nodes, each of these nodes have their respective username. What I am trying to do is, I want to query that Auth object and get all the usernames which is equal to the one I take from a user through input box. In my sql it will be simple as SELECT * FROM auth WHERE username = userInputValue. I need same query like this, Below is what I have done so far.
var _firbaseDB = firebase.database(),
_firebaseAuthRef = _firbaseDB.ref("Auth/");
$("body").on("submit",".search-from",function(e){
e.preventDefault();
var ev = e.target,
_allUsers = $(ev).serializeArray()
_user = _allUsers[0].value;
_firebaseAuthRef.equalTo(_user).on("child_added",function(res){
console.log(res.val());
})
})
You were almost there. What's missing is that you need to specify which attribute you're querying on:
_firebaseAuthRef.orderByChild("n").equalTo(_user).on("child_‌​added",function(res)‌​{
console.log(res.val());
})
More info on the Firebase Database Documentation.

How can i store the registration details in local storage without overwriting it the next time?

So basically i have a registration form and everytime the user registers, i store their data in HTML local storage, but i want the data to look like this for example:
user| [{"username":"Maximillian","password":"whatever","address":""whatever".... and so on. So far i have this code but i am confused with why it doesn't work the way i want it to. And how do i make sure that when another person registers, their details does not overwrite the current register details already on local storage?
You could store an array of the users. For example:
var users = JSON.parse(localStorage.getItem('Users')) || [];
var userData = [{Username:document.getElementById("UserName").value},
{Email:document.getElementById("EmailAddress").value},
{Password:document.getElementById("PassWord").value},
{Address:document.getElementById("Address1").value},
{Phone:document.getElementById("PhoneNumber").value}];
users.push(userData);
localStorage.setItem('Users', JSON.stringify(users));
Then access the users as such:
var users = JSON.parse(localStorage.getItem('Users')) || [];
users.forEach(console.log);
users[0];
users[1];
[etc.]

create and store user objects using localstorage

I am trying to create a user database using localStorage. I just need to store the created user with a unique id so I can reference it as a key later. Right now I have this code in my application.js:
$(document).ready(function() {
$("#signupform").submit(function(e) {
e.preventDefault();
var user = {
name: $('#pname').val(),
email: $('#email').val()
};
localStorage.setItem('user', JSON.stringify(user));
console.log(JSON.parse(localStorage.getItem('user')).name);
var html = new EJS({url: 'templates/usershow.ejs'}).render(user);
var content = document.getElementById('content');
content.innerHTML = content.innerHTML + html;
$("#signupform").remove();
});
});
I need localStorage.setItem('user'... to be something like localStorage.setItem('i'... where "i" increments with each newly created user (like an index) when the submit button is clicked. Would it make more sense to use the user email as the key? That way I can look up each user by their email? How would I go about doing this? Again...I am just trying to set up a user database where I can easily reference users and their info using localStorage. Show me how!
I'd go about incrementing an ID by storing a nextUniqueId in localStorage, then grab that for the key and increment it. Something like this:
function getNextUnique () {
var next = localStorage.getItem('nextUniqueId');
next = next ? parseInt(next) : 0;
var newNext = next + 1;
localStorage.setItem('nextUniqueId', newNext);
return next;
}
Call it whenever you want to save a new user:
localStorage.setItem(getNextUnique(), JSON.stringify(user));
It makes more sense to use the user's email. Simplicity is good.
BUT... this is localStorage. There shouldn't ever be more than one user using it, right? localStorage itself is unique to the client application. Are there really going to be multiple users using the same browser?
If so, then this is fine. But i wonder if you are really thinking about how localStorage works...

Categories

Resources