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!`);
}
}
Related
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));
}
Hi guys I am trying to implement local storage in a little app that I am building but it isn't working. I have been working on it for a long time but I don't know what I am doing wrong so any help would 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));
});
I'm creating a quiz app with an API and plain javascript.
When i fetch the questions from the API, I loop through them and they are displayed one by one. For each question, I read out how many possible answers there are and I create one div for each possible answer.
Where it gets wrong is when I want to click an answer, the next question should show with it's corresponding answer options. So I tried to create an onclick function that removes the created divs and right after that, I call the function that fetches a new question from the iteration and also with corresponding divs. This works well the first time, but after that, nothing happens when I click on any of the options.. It's a bit frustrating
I got recommended to use a reversed loop for deleting the divs.
My Code:
gamePage: () => {
let currentQuestion = {};
let availableQuestions = [];
let questionIndex = 0;
let questioncounter = 0;
let answers = [];
let correctQuestions = [];
let correct = 0;
let id = 0;
let question = document.getElementById('question');
let howMany = document.getElementById('howMany');
let options = document.getElementById('options');
let choises = document.getElementsByClassName('option');
// Personal API Key
const apiKey = '5DLibBNulD2b1v8bYlb7UUO78XNbITbboqwSgdvh';
// The link that will be manipulated
const myLink = `https://quizapi.io/api/v1/questions?apiKey=`
// Allows the user to cancel the game
/** Moet nog een promise in komen met pop up om zeker te zijn dat je wil afsluiten */
function goBackHome() {
const homeButton = document.getElementById('goBackHome');
homeButton.addEventListener('click', () => {
window.location.href = "home.html";
})
}
goBackHome();
// Fetches the questions from the API
const getQuestions = async () => {
const response = await fetch(`${myLink}${apiKey}&category=code&limit=3`, {
});
if(!response.ok) throw new Error('The given response is not OK');
return await response.json();
}
// Iterates over the available questions
const newQuestion = async () => {
questioncounter++;
howMany.innerText = `${questioncounter}/${availableQuestions.length}`
questionIndex = Math.floor(Math.random() * availableQuestions.length);
currentQuestion = availableQuestions[questionIndex];
question.innerHTML = currentQuestion.question;
for (const [option, value] of Object.entries(currentQuestion.answers)) {
if(value != null) {
const div = document.createElement('div');
options.appendChild(div);
div.setAttribute('id', option);
div.classList = 'option';
div.innerText = value;
}
}
};
// Click on a possible answer to go to the next question
const playTheGame = async () => {
for (const choise of choises) {
choise.addEventListener('click', () => {
console.log('the click works');
for (let i = choises.length -1; i >= 0; i--) {
const element = choises[i];
options.removeChild(element);
};
questionIndex++;
newQuestion();
})
}
}
// Game logic
const assemble = async () => {
try {
await getQuestions()
.then((data) => {
availableQuestions = [...data];
console.log(availableQuestions);
const options = document.getElementById('options');
})
await newQuestion();
playTheGame()
} catch (error) {
console.error(error.message)
}
}
assemble();
}
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);
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();