I cannot get the user input to push to Local Storage. When my quizData variable is an empty array it works fine,
let quizData = JSON.parse(localStorage.getItem('MyQuiz'));
and changing it back to this works because (I assume) there is already info in LS,
let quizData = JSON.parse(localStorage.getItem('MyQuiz'));
but clearing LS will cause it to fail again. Any help I can get would be greatly appreciated
let quizData = JSON.parse(localStorage.getItem('MyQuiz'));
const addQuiz = (ev) => {
ev.preventDefault();
let quizForm = {
question: document.getElementById('question-input').value,
a: document.getElementById('a-input').value,
b: document.getElementById('b-input').value,
c: document.getElementById('c-input').value,
d: document.getElementById('d-input').value,
correct: document.getElementById('correct-input').value,
};
quizData.push(quizForm);
document.forms[0].reset();
console.warn('added', { quizData });
localStorage.setItem('MyQuiz', JSON.stringify(quizData));
};
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('submitForm').addEventListener('click', addQuiz);
console.log(quizData);
});
and the error custom-questions.js:26
Uncaught TypeError: Cannot read properties of null (reading 'push') at HTMLButtonElement.addQuiz
CodePudding user response:
You can simply set the quizData
to a new array if there's nothing in the localStorage
.
let quizData = JSON.parse(localStorage.getItem('MyQuiz')) ?? [];
If quizData
is updated elsewhere, it is better to retrieve the latest array before updating it. So you can get the latest quizData
inside addQuiz
.
const addQuiz = (ev) => {
ev.preventDefault();
let quizForm = {
question: document.getElementById('question-input').value,
a: document.getElementById('a-input').value,
b: document.getElementById('b-input').value,
c: document.getElementById('c-input').value,
d: document.getElementById('d-input').value,
correct: document.getElementById('correct-input').value,
};
const quizData = JSON.parse(localStorage.getItem('MyQuiz')) ?? [];
quizData.push(quizForm);
document.forms[0].reset();
console.warn('added', { quizData });
localStorage.setItem('MyQuiz', JSON.stringify(quizData));
};
CodePudding user response:
You should initialize quizData as empty array if null or undefined.
let quizData = JSON.parse(localStorage.getItem('MyQuiz')) || [];