I am following a tutorial and I understood everything up until everything beyond where I declared the let variable.
function submitMessage(event) {
event.preventDefault();
const email = document.getElementById("email").value;
const fullName = document.getElementById("fullName").value;
const feedbackType = document.getElementById("feedbackType").value;
const comment = document.getElementById("comment").value;
const messageObject = {
email,
fullName,
feedbackType,
comment
};
let currentMessages = [];
if (window.sessionStorage.getItem("messages")) {
currentMessages =
JSON.parse(
window.sessionStorage.getItem("messages")
);
}
currentMessages.push(messageObject);
window.sessionStorage.setItem(
"messages",
JSON.stringify(currentMessages)
);
}
CodePudding user response:
You're setting the "messages"
key for the session storage here:
window.sessionStorage.setItem(
"messages", // arbitrary key name
JSON.stringify(currentMessages) // value to store for this key
);
CodePudding user response:
let currentMessage
is an empty array that will hold messageObject
variable expressed few row before.
After currentMessage
there is a step that setup a session store that we going to call "messages".
The window.sessionStorage
function is used to save some data inside the browser, in our case currentMessage
. In this way if your refreshed the browser page you will able to get the last data save in window.sessionStorage
.
So in the first step this function try to get messages object from the session storage that we have e called messages
.
Then, one fetched it will push the currentMessage
inside it with setItem
, so after you reload the browser you will be able to retrieve the array passing through the session storage getItem
and to get this value it need to search inside some key and the key is messages
, in other word the key in the session storage that can hold our array.