I was given a project to do for practice, the idea of the project is to create a create a form that I will create a timesheet, store in local storage and display it every data stored in a table . I’m using an array to store all the user inputs as objects and then use push method store it inside the localStorage.
Everything seems to work as I want, even when I refresh the page the localStorage is still intact. However when the user makes a new input, the localStorage gets overwritten.
this is my code
I create a function to save the data in array form inside localstorage,
I used push method
const addTask = document.querySelector("#submit");
let timeSheets =
localStorage.getItem("timeSheets") !== null
? JSON.parse(localStorage.getItem("timeSheets"))
: [];
addTask.addEventListener("click", (event) => {
event.preventDefault();
console.log("Btn Clicked");
saveData();
// showData();
});
function saveData() {
const record = {
// id: document.getElementById("id").value,
task: document.getElementById("task").value,
timeStart: document.getElementById("timestart").value,
timeStop: document.getElementById("timestop").value,
};
timeSheets.push(record);
// timeSheets.unshift(record);
localStorage.setItem("timesheets", JSON.stringify(timeSheets));
console.log(timeSheets);
}
My Result in the console:
[{…}]
0
:
{id: 332, task: '1', timeStart: '11:45', timeStop: '17:45', date: '2024-05-29'}
1
:
{id: 329, task: '1', timeStart: '11:45', timeStop: '17:45', date: '2024-05-29'}
2
:
{id: 90, task: '1', timeStart: '11:45', timeStop: '17:45', date: '2024-05-29'}
length
:
3
After refreshing or close the browser, and there is new input, it overwrites
[{…}]
0
:
{id: 0, task: '3', timeStart: '10:50', timeStop: '11:50', date: '2024-06-07'}
length
:
1
[[Prototype]]
:
Array(0)
I expect the new input to add to the existing one
header 1 | header 2 |
---|---|
cell 1 | cell 2 |
cell 3 | cell 4 |
header 2 |
---|
cell 2 |
cell 4 |