Writing and Reading JSON files in javascript - javascript

So I am doing a project right now requiring the storage of user preferences with JSON. I have searched for a decent amount of time now but can find no solution.For example sake There are three variables user, permissions, serverid . I figured this would work.
tempObject = {
user: []
};
tempObject.user.push({perm:permissions, server:serverid});
Then i would stringify and turn into a JSON. However the output came out like this:
{user[{perm:4, server:883}]}
This was my desperate attempt at grouping the perm and server variables under the indivisuals UserID so further down in the code i can fetch the permissions of each userID. But as you can see it didnt print the user variable, just changed it to an array and took user as a litteral string.
tl;dr
In short i need help being able to have a JSON file be written to where it stores the perm and serverID under the UserID.

Make user an object. Change this:
user: []
for this:
user: {}
and then set the keys like this:
user.perm = 4;
user.server = 883;

For security reasons, client-side JavaScript is not permitted to write to the disk. This sounds like you need a database.
You could leverage localStorage, or perhaps a cookie as an alternate to a database.
I think you should change the users array to an object; that way could key by userID.
for example:
var data = {
users: {}
};
const userID = 1234; // or could be a string like 'john_doe'
const userPermissions = { perm: 4, server: 883 };
// set the user's permissions
data.users[userID] = userPermissions;
// fetching user's permissions
const userData = data.users[userID];
console.log('User ' + userID +' has perm = ' + userData.perm + ' and server = ' + userData.server);
Now saving and loading of this data using local storage is easy:
function saveData() {
localStorage.setItem('UserData', JSON.stringify(data));
}
function loadData() {
data = JSON.parse(localStorage.getItem('UserData'));
}

Related

displaying local storage values

I am trying to display only the values which are saved inside of the local storage and not the key value which will show all the data in the local storage after the login form has been submitted
welcome <span id="demo"></span>
<script>
document.getElementById('demo').innerHTML=localStorage.getItem ("users") === ("username");
</script>
Please try this.
let userData = localStorage.getItem ("users") ;
if(userData) {
userData = JSON.parse(userData);
document.getElementById('demo').innerHTML = userData[0]['username'];
}
Hope this will solve your problem.
Ok first of all, you really should not save the password in your localStorage.
The user (Not users) should be an object that is holding ONLY public information that you don't mind even other websites to have access to.
And it should be something like {username: "Something", email: "something#tada.com"}
By that you can use it like this:
let user = localStorage.getItem('user');
if (user) {
user = JSON.parse(user);
document.getElementById('demo').innerHTML = user.username;
}

Referencing firebase database with a variable and string concatenation

As you can see below i'm trying to read a list of data from the database and then loop over the result, in javascript. The function runs whenever i open/refresh the page:
firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {
snapshot.forEach(function(e) {
var element = e.val();
var roomId = element.Id;
});
});
However, that string concatenation to specify the User Id doesn't work for some reason. When i replace it with the user Id directly like this:
firebase.database().ref("Users/GR3JFsMrKOjCrLhDNFMaq72COd07/rooms").on.....
that works fine. But of course i want to use the variable which contains the Id of the current user.
The uid variable is assigned a value in the onAuthStateChanged when checking if the user is signed in:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
uid = user.uid;
If I add a console.log like this:
firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {
console.log(snapshot.parent);
snapshot.forEach(function(e) {
the output with the first code example (using uid variable) is: undefined.
If i specify the User Id directly it is: room-id-1 (the result i want).
How do i make the string concatenation work? Or is this the wrong way of specifying the path of the current user?
It is extremely unlikely that the problem is in the string concatenation itself. It is much more likely that uid simple doesn't have a value yet when you start reading from the database.
To make sure the uid is available, put the reading of the data into the auth state listener like this:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
uid = user.uid;
console.log("uid="+uid);
firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {
snapshot.forEach(function(e) {
var element = e.val();
var roomId = element.Id;
console.log("roodId="+roomId);
});
});
}
})

Firebase - Update specific fields simultaneously without replacing all of the data

I would like to be able to publish simultaneously in two directories of my Firebase database. I created a function for this, according to the example proposed in the "Update specific fields" section of the Firebase Javascript documentation:
function linkTwoUsers(user1, user2) {
// The two users are "connected".
var user1Data = {
userLink: user2
};
var user2Data = {
userLink: user1
};
var updates = {};
updates["/users/" + user1] = user1Data;
updates["/users/" + user2] = user2Data;
return database
.ref()
.update(updates)
.then(() => {
return res.status(200).end();
})
.catch(error => {
return res.status(500).send("Error: " + error.message);
});
}
The problem is that when I run the function, instead of uploading the directories, it replaces all the data present in it.
Here are the user directories before the function:
And then:
How do we make sure the data doesn't overwrite the others? Thank you for your help.
Try to narrow your path to just the property you are trying to update:
updates["/users/" + user1 + "/userLink/"] = user1;
updates["/users/" + user2 + "/userLink/"] = user2;
It seems as though you're creating an entirely new object when you set:
var userData = { someThing: stuff }
When you pass that in, it will override the original object. One way you might solve this (there might be a more efficient way) is to grab the objects from Firebase, add the new property and value to the object, then send the entire object back into Firebase.
In some javascript frameworks, you should be able to use the spread operator to set all of an object's props to another object like this:
var newObject = { ...originalObject }
newObject.userData = "something"
// then save newObject to firebase

Write an uploads metadata with information stored data in Firebase DB

I've been hitting my head against the wall on this for about 2 hours and I think I've just lost sight of the problem a bit.
I have an incremental field saved as "index" that upon a file upload starting has it's value increase by 1.
I am able to query the database and pull the value for index to the console and receive the updated value.
I can't for the life of me work out how to insert the value I've created and subsequently logged to the console (definitely doesn't need to be logged just did this to prove to myself I wasn't going insane) into the uploads metadata at the next stage of the script. I have tried everything I can think of - I've watched about an hour of youtube videos, and I can safely say beyond a shadow of a doubt I could turn my app into a running counter of peoples file uploads but I can't add it to their upload metadata!
Help me stack overflow you're my only hope!
Code below hopefully outlines the issue - the query is going into the variable indexRef but the actual info I need is in the nested variable "key" which is just the data snapshot value. This seems like it should be so easy.
var indexRef = firebase.database().ref('index');
indexRef.once('value')
.then(function(snapshot){
var key = snapshot.val()
console.log(key)
})
var imagekey = firebase.database().ref('images/').push().key;
var downloadURL = uploadTask.snapshot.downloadURL;
var updates = {};
var postData = {
url: downloadURL,
score: 1500,
index: indexRef,
user: user.uid
};
updates ['/images/'+imagekey] = postData;
firebase.database().ref().update(updates);
Thanks in advance and I apologise if the answer to this is trivial and I've wasted someones time!
Remember the then method returns promises https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html
var indexRef = firebase.database().ref('index');
// Declare variables outside of block to access within
var imagekey = firebase.database().ref('images/').push().key;
var downloadURL = uploadTask.snapshot.downloadURL;
var updates = {};
indexRef.once('value')
.then(function(snapshot){
var key = snapshot.val()
// Return key variable for use
return key;
})
.then(function(key){
// You can now access the key variable in here
var postData = {
url: downloadURL,
score: 1500,
index: key,
user: user.uid
};
updates ['/images/'+imagekey] = postData;
firebase.database().ref().update(updates);
})
Hope this helps you

Checking data in deep array with includes (Firebase retrieve data JS)

So I am new to the Firebase database and what I like about it is that I don't have to build a whole backend for just storing some simple data. What I am trying to do is pushing data to an array that I like to recieve from firebase. Then after that I would like to check if the email that was filled in, is included in the data from the firebase database. But because it's firebase and it has multiple arrays, objects etc I don't know how to check that. So the flow is: User fills in data, Applications makes a call to the firebase db and the Application is retrieving the current data from firebase. Then the Application will check if the data that is inputed is already there, and if so, will throw an alert that the data is already in the database. If not, the data will be submitted.
Also, I am wondering if this is the right way to retrieve data from the database:
Main.js
function writeUserData() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
firebase.database().ref('/aanmeldingen/').push({
username: name,
email: email,
});
var dbRef = firebase.database().ref().child('/aanmeldingen/');
dbRef.on('value', snapshot => {
const snap = snapshot.val();
const array = [];
array.push(snap);
console.log(array);
const res = array.includes(email);
console.log(res);
console.log(email);
});
}
Output in console
As you can see this returns multiple data. The include function will check on the submitted emailadress. This returns false even I had inputted "info#webpack.com". How can I check the right data object? It has to check all objects under "0" and return in the console if the submitted emailadress is already there.
I haven't tested it yet but i hope you get the idea. Also this is not the most efficient way to do this.
function ifEmailExist(arr,email){
var _t = 0;
for(var x in arr){
for(var y in arr[x]){
if(arr[x][y].email){
if(arr[x][y] === email){
_t++;
}
}
}
}
return _t;
}
Usage:
if(ifEmailExist(arr,"info#webpack.com") > 0){
//do stuff
}
You should use child_added instead of value. Whenever a new node is added in database, child_added will trigger and then you can take action on the data.
var dbRef = firebase.database().ref().child('aanmeldingen');
dbRef.on('child_added', snapshot => {
var username = snapshot.val().username;
var email = snapshot.val().email;
console.log(username);
console.log(email);
});

Categories