Filter data from local storage - javascript

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];

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 set Firebase snapshot data into array in sessionStorage

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

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.

#ionic change the data key in firebase

I'm trying to update/add data on firebase. I used the Facebook login and I want to use the UserID as a key for the new data aded.
(check pict below)
The userID that I want to use it:
I want to replace that key with the userID:
fblogin(){
this.facebook.login(['email'])
.then(res=> {
const fc = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
firebase.auth().signInWithCredential(fc)
.then(fs => {
this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height(720).as(picture_large)', []).then(profile => {
this.newuser = {name: profile['first_name'] ,email: profile['email'],picture: profile['picture_large']['data']['url'],phone:''}
this.navCtrl.push(HomePage);
console.log(fs.uid);
this.db.list('/users/'+ fs.uid).update(this.newuser);
});
I got this error in compilation:
supplied parameters do not matchany signature of call target
In this line: this.db.list('/users/'+ fs.uid).update(this.newuser);
Any help?
The FB error looks correct. You cant update on the uid as the user has been saved with a unique FB id
You do not show the code that created the users record in the database, but what i think you want to do is set and object when you first save the users record. However this could be an issue because the user could be saved before the return of the uid. I cant tell with your code snippet. Regardless, I will write the code that i think will work if the users/ record is created at the time that of registration.
The service
async signupUser(email: string, password: string) {
try {
const result = await this.afA.auth.createUserWithEmailAndPassword(email, password);
return result;
} catch (err) {
console.log('error', err);
}
}
So this initially creates a user without facebook, The key here is that the users FB uid was created and is held in the returned result
The component
this.authData.signupUser(email,password).then(userData => {
console.log(userData) // <- this is result
}
Then we create a record in FB with the uid returned
this.db.object(`users/${userData.uid}/`).set(data);
.set(data) is whatever data you want to save in the users/uid namespace.
So basically you need to create that user table with its uid namespace when the user first registers. Then you can update the user with the uid returned from the facebook fs.uid
With your current code you could find the user based on the email ( because the email should be unique to all users) and then update ...
with lodash is it just
let foundUser = find(this.db.list('users'),{ 'email' : fs.email }
// and then update based on the object key
this.db.list('/users/'+ Object.keys(foundUser)).update(this.newuser);
i fixed the problem by using:
this.db.object('/users/'+ fs.uid).update(this.newuser);
instead of :
this.db.list('/users/'+ fs.uid).update(this.newuser);
And it works correctly !
Thanks all for help.

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.]

Categories

Resources