How to set Firebase snapshot data into array in sessionStorage - javascript

var db1 = firebase.firestore();//API firestore database
var docRef1 = db1.collection("SuccessTransaction");
var showSeat = docRef1.get().then(function(snapshot){
snapshot.forEach(function(doc){
if(doc.exists){
alert(doc.data().Seat);
sessionStorage.setItem("routeUnavailableSeat", JSON.stringify(doc.data().Seat));
}else{
alert("No such documet!");
}
});
}).catch(function(error){
alert("Error getting document!", error);
});
I had a problem with this kind of situation. My intention was to set my snapshot value and set it into sessionStorage. The problem is after the system run, it will replace the old data and replace the new data. How can I using array or other method in order to keep all my data in sessionStorage?

The local storage API (that session storage is based on) can only store string values. So to store your values as an array, you will need to encode the array in a string.
Aside from that, it's a matter of getting the current value, parsing it, and then adding it back into session storage:
if(doc.exists){
let value = sessionStorage.getItem("routeUnavailableSeat");
let seats = current ? JSON.parse(current) : [];
seats.push(doc.data().Seat)
sessionStorage.setItem("routeUnavailableSeat", seats);
}

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 check if value exists in realtime database firebase

I have created a realtime database on firebase and having no issues adding and removing data in tables etc.
I currently have it setup like this:
So my goal is to check if a given value is inside my database currently.
for example, I would like to check if 'max' is currently a username in my database.
var data = db.ref('loginInfo/');
data.on('value', function(snapshot) {
_this.users = snapshot.val()
});
That is how I get all the values, it is saved into _this.users
(How do i check if a value is inside this object, i am making a login program)
if i console.log the object, this is what I see:
image
If you want to check if a child node exists under loginInfo where the username property has a value of max, you can use the following query for that:
var ref = db.ref('loginInfo/');
var query = ref.orderByChild('username').equalTo('max');
query.once('value', function(snapshot) {
console.log(snapshot.exists());
});
I'd also recommend reading the Firebase documentation on queries, as there are many more options.

Filter data from local storage

I have few datas stored in local storage as array of objects, like
[{"id":0,"firstname":"test","lastname":"test","email":"test#test.com"},
{"id":1,"firstname":"demo","lastname":"demo","email":"demo#demo.com"}];
I want to display the data of user logged in, in the text box. When I am writing localStorage.getItem('key_users'), its showing me details of all users, but how to get detail of a user of a particular index?
As a function
function getUserById(id) {
return JSON.parse(localStorage.getItem('users')).filter(users => users.id === id)
}
getUserById(0)
Easy: deserialize local storage's item using JSON.parse:
var users = JSON.parse(localStorage.getItem('key_users'));
var user0 = users[0];

Adding to existing Firebase integer

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
})
})}

Making an Array Variable Global in JavaScript

I'm setting a an array variable to 0 on load of my javascript.
var postArray= new Array();
However, I used this array to hold my objects that I retrieve from localStorage. It works when I upload more blog posts that get entered into localStorage and displays. However, after I refresh the page this is called again as is an empty array and say I go to enter my 3rd blog post after i've refreshed, my localStorage is set to only having the contents of my postArray. Therefore, I'm clearing out my localStorage when I dont want to.
if you throw it into an if statement, postArray is undefined.
if (localStorage.getItem("posts") === null) {
var postArray = new Array();
}
I'm trying to make the postArray global at the start yet only create a new array when localStorage is empty.
You should just get the content from the localStorage, and if it's empty, then return an empty array.
For example.
var postArray= getPosts();
function getPosts() {
var posts = localStorage.getItem("posts");
return posts ? JSON.parse(posts) : [];
}
i think you should use document coockie instead of array !!
when page is load read the cookie content if it's empty "localStorage" then store the "whatEver you want" value on its ! this is better than arrays

Categories

Resources