How can I make changing text with Firebase Database? - javascript

I have this code to get some text from Firebase Database
var reviewID = 0;
var dataRef = firebase.database().ref("reviews/" + reviewID);
function getReview() {
dataRef.once("value").then(function (snapshot) {
const reviewName = snapshot.val().name;
const reviewText = snapshot.val().text;
const reviewDate = snapshot.val().date;
$('#reviewName').html(reviewName);
$('#reviewText').html(reviewText);
$('#reviewDate').html(reviewDate);
});
};
getReview();
And I have this structure in Firebase.
I want button to change reviewID so I must get different values of reviewName, reviewText and reviewDate. Here is code for this button:
$('#reviewButtonRight').click(function () {
reviewID += 1;
getReview();
});
But it doesn't work. So how can I fix it?

You need to create a new ref each time
var reviewID = 0;
var reviewRef = firebase.database().ref("reviews");
function getReview() {
const review = reviewRef.child(reviewID);
review.once("value").then(function (snapshot) {
const reviewName = snapshot.val().name;
const reviewText = snapshot.val().text;
const reviewDate = snapshot.val().date;
$('#reviewName').html(reviewName);
$('#reviewText').html(reviewText);
$('#reviewDate').html(reviewDate);
});
};
getReview();

Related

I am having trouble pushing form values to an array in a leaderboard app

Hi guys I am trying to make a small leaderboard app and I am having problems saving the values in the form. When I try to push the information to the array it is empty and I am rendering nothing, Any help would be appreciated.
Also, my local storage isn't working properly any help on that would also be appreciated.
#Javascript
const form = document.querySelector('.form');
const scores = JSON.parse(localStorage.getItem('scores')) || [];
function saveScore() {
const name = document.querySelector('.fullname').value;
const score = document.querySelector('.thescore').value;
const newScore = {
name,
score,
};
scores.push(newScore);
localStorage.setItem('scores', JSON.stringify(scores));
}
function renderScores() {
const scoreList = document.querySelector('.result-list');
scoreList.innerHTML = '';
scores.forEach((score) => {
const li = document.createElement('li');
li.innerHTML = `${score.name} : ${score.score}`;
scoreList.appendChild(li);
localStorage.setItem('scores', JSON.stringify(scores));
});
}
form.addEventListener('submit', (e) => {
e.preventDefault();
saveScore();
renderScores();
localStorage.setItem('scores', JSON.stringify(scores));
});
You have to put the saveScore function in the eventListener.
This will set the name and score in local storage.
const form = document.querySelector('.form');
const scores = JSON.parse(localStorage.getItem('scores')) || [];
form.addEventListener('submit', (e) => {
e.preventDefault();
// inside now
saveScore();
});
function saveScore() {
const name = document.querySelector('.fullname').value;
const score = document.querySelector('.thescore').value;
const newScore = {
name,
score,
};
scores.push(newScore);
localStorage.setItem('scores', JSON.stringify(scores));
}
I think saveScore(); never happen. Could you try invoke saveScore(); after e.prevendDefault() inside event callback.
Then after event 'submit' will happen you will trigger the saveScore and save values. I hope that will help.
Do it like this:
var arr = [];
function saveScore() {
const name = document.querySelector('.fullname').value;
const score = document.querySelector('.thescore').value;
var newScore = {};
newScore.name = name;
newScore.score = score;
arr.push(newScore);
localStorage.setItem('arr', JSON.stringify(scores));
}

Updating the query data in cloud firestore nested map fields

I'm trying to update the data in nested map fields in firestore, my form is a window form that has 4 sides (wSide1,wSide2,wSide3,wSide4), what my form is doing is if customer select 1 field which is wSide1 and it needs to be updated then only this field only be updated but in my case it is updating all 4 sides, the one which is selected for example side 1 only that has the correct updated values other 3 sides updates with the false values. as my form is dynamic it only shows the field which is selected.
I only want to update the field which is selected, all other has to be null.
js & firestore query
function updateWindowForm(form, type){
var name = $('#name_'+type).val();
var type = $('#type_'+type).val();
const taskformWindow = document.getElementById("taskformWindow");
let editStatus = false;
let id = '';
const updateTask = (id, updatedTask) => db.collection('Buildings').doc(buildingID).collection('rooms').doc(roomID).collection('objects').doc(objectID).update(updatedTask);
window.addEventListener("DOMContentLoaded", async (e) => {
id = doc.id;
editStatus = true;
btnsEdit.forEach((btn) => {
btn.addEventListener("click", async (e) => {
try {
const doc = await getTask(e.target.dataset.id);
const task = doc.data();
editStatus = true;
id = doc.id;
taskformWindow["btn-update-data"].innerText = "Update";
} catch (error) {
console.log(error);
}
});
});
});
taskformWindow.addEventListener("click", async (e) => {
e.preventDefault();
var name_Window = document.getElementById('name_Window').value;
var wAluminium = document.getElementById('wAluminium').checked;
var wColorMeasurement = document.getElementById('wColorMeasurement').value;
var wComments = document.getElementById('wComments').value;
var wForEnd1 = document.getElementById('wForEnd1').checked;
var wForEnd2 = document.getElementById('wForEnd2').checked;
var wSideOfWindows = document.getElementById('wSideOfWindows').value;
var wHardwareManufacturer = document.getElementById('wHardwareManufacturer').value;
var wPlastic = document.getElementById('wPlastic').checked;
//Side 1
var wAxis1_1 = document.getElementById('wAxis1_1').checked;
var wAxis1_2 = document.getElementById('wAxis1_2').checked;
var wBackSet1 = document.getElementById('wBackSet1').value;
var wDirectionLR1_1 = document.getElementById('wDirectionLR1_1').checked;
var wDirectionLR1_2 = document.getElementById('wDirectionLR1_2').checked;
var wHandleHeight1 = document.getElementById('wHandleHeight1').value;
var wOverlapWidth1 = document.getElementById('wOverlapWidth1').value;
var wSashRebateHeight1 = document.getElementById('wSashRebateHeight1').value;
var wSashRebateWidth1 = document.getElementById('wSashRebateWidth1').value;
//Side 2
var wAxis2_1 = document.getElementById('wAxis2_1').checked;
var wAxis2_2 = document.getElementById('wAxis2_2').checked;
var wBackSet2 = document.getElementById('wBackSet2').value;
var wDirectionLR2_1 = document.getElementById('wDirectionLR2_1').checked;
var wDirectionLR2_2 = document.getElementById('wDirectionLR2_2').checked;
var wHandleHeight2 = document.getElementById('wHandleHeight2').value;
var wOverlapWidth2 = document.getElementById('wOverlapWidth2').value;
var wSashRebateHeight2 = document.getElementById('wSashRebateHeight2').value;
var wSashRebateWidth2 = document.getElementById('wSashRebateWidth2').value;
//Side 3
var wAxis3_1 = document.getElementById('wAxis3_1').checked;
var wAxis3_2 = document.getElementById('wAxis3_2').checked;
var wBackSet3 = document.getElementById('wBackSet3').value;
var wDirectionLR3_1 = document.getElementById('wDirectionLR3_1').checked;
var wDirectionLR3_2 = document.getElementById('wDirectionLR3_2').checked;
var wHandleHeight3 = document.getElementById('wHandleHeight3').value;
var wOverlapWidth3 = document.getElementById('wOverlapWidth3').value;
var wSashRebateHeight3 = document.getElementById('wSashRebateHeight3').value;
var wSashRebateWidth3 = document.getElementById('wSashRebateWidth3').value;
//Side 4
var wAxis4_1 = document.getElementById('wAxis4_1').checked;
var wAxis4_2 = document.getElementById('wAxis4_2').checked;
var wBackSet4 = document.getElementById('wBackSet4').value;
var wDirectionLR4_1 = document.getElementById('wDirectionLR4_1').checked;
var wDirectionLR4_2 = document.getElementById('wDirectionLR4_2').checked;
var wHandleHeight4 = document.getElementById('wHandleHeight4').value;
var wOverlapWidth4 = document.getElementById('wOverlapWidth4').value;
var wSashRebateHeight4 = document.getElementById('wSashRebateHeight4').value;
var wSashRebateWidth4 = document.getElementById('wSashRebateWidth4').value;
try {
if (!editStatus) {
await updateTask(id, {
name:name_Window,
Form:{
wAluminium: wAluminium,
wColorMeasurement: wColorMeasurement,
wComments: wComments,
wForEnd1: wForEnd1,
wForEnd2: wForEnd2,
wHardwareManufacturer: wHardwareManufacturer,
wPlastic: wPlastic,
wSide1:{
wAxis1_1: wAxis1_1,
wAxis1_2: wAxis1_2,
wBackSet1: wBackSet1,
wDirectionLR1_1: wDirectionLR1_1,
wDirectionLR1_2: wDirectionLR1_2,
wHandleHeight1: wHandleHeight1,
wOverlapWidth1: wOverlapWidth1,
wSashRebateHeight1: wSashRebateHeight1,
wSashRebateWidth1: wSashRebateWidth1,
},
wSide2:{
wAxis2_1: wAxis2_1,
wAxis2_2: wAxis2_2,
wBackSet1: wBackSet2,
wDirectionLR2_1: wDirectionLR2_1,
wDirectionLR2_2: wDirectionLR2_2,
wHandleHeight2: wHandleHeight2,
wOverlapWidth2: wOverlapWidth2,
wSashRebateHeight2: wSashRebateHeight2,
wSashRebateWidth2: wSashRebateWidth2,
},
wSide3:{
wAxis3_1: wAxis3_1,
wAxis3_2: wAxis3_2,
wBackSet1: wBackSet3,
wDirectionLR3_1: wDirectionLR3_1,
wDirectionLR3_2: wDirectionLR3_2,
wHandleHeight3: wHandleHeight3,
wOverlapWidth3: wOverlapWidth3,
wSashRebateHeight3: wSashRebateHeight3,
wSashRebateWidth3: wSashRebateWidth3,
},
wSide4:{
wAxis4_1: wAxis4_1,
wAxis4_2: wAxis4_2,
wBackSet4: wBackSet4,
wDirectionLR4_1: wDirectionLR4_1,
wDirectionLR4_2: wDirectionLR4_2,
wHandleHeight4: wHandleHeight4,
wOverlapWidth4: wOverlapWidth4,
wSashRebateHeight4: wSashRebateHeight4,
wSashRebateWidth4: wSashRebateWidth4,
},
wSideOfWindows: wSideOfWindows,
}
})
editStatus = false;
id = '';
taskformWindow['btn-update-window-data'].innerText = 'Daten aktualisiert';
swal("", "Daten wurden aktualisert!", "success");
}
taskformWindow.reset();
} catch (error) {
console.log(error);
}
});
}
I can't see the code you use for updating your data but I can ausme that you probably did not set the merge to true while saving the data.
Take a look at this code snipped:
var cityRef = db.collection('cities').doc('BJ');
var setWithMerge = cityRef.set({
capital: true
}, { merge: true });
By setting that we ensure to udate only the fields we want to and leave the rest as it is. Still make sure not to send fields with a null value because that is a valid value for firestore and it doesn't mean that those fields will by skipped in the update process. You can find more about it here.

How can i collect all the data from the name value so i can use it?

let inpPas = document.querySelector('#inpPas');
let btnGo = document.querySelector('#btnGo');
const db = firebase.database();
let ref = db.ref('xVerdi');
let rootRef = firebase.database().ref().child('xVerdi');
rootRef.on('child_added', snap => {
let name = snap.child('name').val();
btnGo.onclick = goPassword;
function goPassword(){
if (inpPas.value == name) {
alert("yeyeye")
}
console.log("her " + name)
}
console.log(name)
})
I want to use all the data that i have stored in this name: value, but i can only use the most resent one. Any suggestions?
Do the following:
let nameList = [];
let rootRef = firebase.database().ref().child('xVerdi');
rootRef.on('child_added', snap => {
let name = snap.child('name').val();
nameList.push(name);

How do I delete all records in IndexedDB

I have an IndexedDB where I store all cart orders. On checkout, the cart needs to be clear. I'm trying to loop through each order and delete, but somehow, only the first order gets deleted. Here is my code:
const clear_cart = () => {
let objectCart = db.transaction('cart').objectStore('cart');
objectCart.openCursor().onsuccess = function(e){
let cursor = e.target.result;
if(cursor){
let cartId = cursor.value.id;
let transaction = db.transaction(['cart'], 'readwrite');
let objectToDelete = transaction.objectStore('cart');
let request = objectCart.objectToDelete(cartId);
transaction.oncomplete = () => {
console.log(`cart ${cartId} is deleted!`);
}
cursor.continue();
}
}
}
I made some tweaks to the suggestion of dmigo and this solved my problem. Here is the code
const clear_cart = () => {
let objectCart = db.transaction('cart').objectStore('cart');
let transaction = db.transaction(['cart'], 'readwrite');
let objectToDelete = transaction.objectStore('cart');
objectToDelete.clear().onsuccess = function(e){
console.log(`the cart is clear!`);
}
}
I would try the clear method of the objectStore.
const clear_cart = () => {
let objectCart = db.transaction(['cart'], 'readwrite').objectStore('cart');
objectCart.clear().onsuccess = function(e){
console.log(`the cart is clear!`);
}
}

Firestore auth, use user UID to doc id with ionic

i'm trying to use user UID for id of a doc when an user is signup.
in service.ts, I have this line :
create_NewStudent(record) {
return this.firestore.collection('users').add(record);
}
And this is my signup function
signup() {
this.afAuth.auth
.createUserWithEmailAndPassword(this.email, this.pass)
.then( token => {
console.log(token.user.uid)
});
let record = {};
record['nom'] = this.nom;
record['prenom'] = this.prenom;
record['email'] = this.email;
record['pass'] = this.pass;
record['datenaissance'] = this.datenaissance;
record['lieunaissance'] = this.lieunaissance;
record['adresse'] = this.adresse;
record['codepostal'] = this.codepostal;
record['ville'] = this.ville;
record['tel'] = this.tel;
record['secu'] = this.secu;
record['equipe'] = this.equipe;
record['poste'] = this.poste;
this.UsersService.create_NewStudent(uid,record).then(resp => {
this.nom = "";
this.prenom = "";
this.email = "";
this.pass = "";
this.datenaissance = "";
this.lieunaissance = "";
this.adresse = "";
this.codepostal = "";
this.ville = "";
this.tel = "";
this.secu = "";
this.equipe = "";
this.poste = "";
console.log(resp);
})
.then(() => {
this.modalCtrl.dismiss();
});
}
For now, when new signup -> it's generate an doc id, but how to use user uid as doc id
Thanks you for help
using add() will create the new document under a randomly generated id. Assuming you have a way to get your user id. You can put it into firestore using
this.firestore.collection('users').doc(uid).set(record);
To get the uid at signup
signup() {
this.afAuth.auth
.createUserWithEmailAndPassword(this.email, this.pass).then( token => {
console.log(token.user.uid)
});

Categories

Resources