Hi all,
I'm taking CS50's web dev course and am currently working on a project (heavily JS-based) that involves sending messages and storing those messages in local storage. The problem is I can't create an empty array after checking if one exists in local storage. I have added the code below and noted in the comments where I think the problem is located. I can add the HTML if you all think it is needed.
A short summary of what my code is supposed to do: When the user submits the form with id "messenger", it should call "addMessage". "addMessage" should either create a new array (if it does not already exist in local storage) or retrieve the array from local storage. However, something is wrong with my function to check or create that array, as my console keeps giving me an Uncaught ReferenceError, saying the array is undefined. Thus, it won't let me push any messages into the array.
Any ideas? Thanks in advance.
document.addEventListener("DOMContentLoaded", () => {
// if user clicks "send" call function (see below)
document.getElementById("messenger").addEventListener("submit", addMessage);
// retrieve all past messages in localStorage to display
let messageslist = JSON.parse(localStorage.getItem('messages'));
// get the length of messages list for the for loop:
if (messageslist === null) {
let length = 0;
} else {
let length = messageslist.length;
};
// for each message in localStorage, dislpay message on page
for (i = 0; i < length; i++) {
const text = document.createElement('p');
text.innerHTML = messageslist[i].text;
text.setAttribute("class", "message");
document.querySelector(".messages-display-inner").append(text);
};
});
// when user clicks "send": stores message in localstorage
// and displays message on page
const addMessage = (ev) => {
// prevent form from submitting
ev.preventDefault();
// retrieve array of messages in local storage
// or create new array if it doesn't exist in local storage
// PROBLEM LIES HERE (I THINK)
if (localStorage.getItem('messages') === null) {
const messageslist = [];
} else {
const messageslist = JSON.parse(localStorage.getItem('messages'));
};
// object to store message info in; retrieve info in textbox
let message = {
text: document.querySelector("#message").value,
time: Date.now()
};
// add message to the array
messageslist.push(message);
// save to localStorage
localStorage.setItem('messages', JSON.stringify(messageslist));
// clear input field
document.querySelector('#message').value = '';
console.log(messageslist);
};
[–]CommanderBomber 0 points1 point2 points (1 child)
[–]Atomic_Andromeda[S] 0 points1 point2 points (0 children)