I want a localStorage to be programmatically defined. I have an array of values in it Just want the localStorage to take it and define new storage. Like if a click a button it should define a localStorage as 'session 0' with the value from the array and If I click it the second time it should define another localStorage as 'session 1'. But after I close the window and open it and click the button the new localStorage should be continued like 'session 2' not start over from 0.
And it should check if the previous localStorage does have a value or not. Like if I am defining 'session 3' it should check if 'session 2' exists and have a value.
But what problem I am overcoming is after I close the window and start the process the localStorage doesn't start off from where it left if starts from 0 and redefines the storage that was declared first.
Fakearr consists of the value.
This is what I have tried.
for (let i = 0; i <= fakearr.length; i++) {
if (
(localStorage.getItem(`session ${i}`) == null &&
localStorage.getItem(`session ${i - 1}`).length >= 0) ||
localStorage.length == 0
) {
localStorage.setItem(`session ${i}`, JSON.stringify(fakearr[i]));
}
}
What about something like this:
function maxSessionID(){
let i = 0;
while (localStorage.getItem(`session${i}`) !== null ) {
i++;
}
return i;
}
for (let i = 0; i < fakearr.length; i++) {
localStorage.setItem(`session${maxSessionID()+1}`, JSON.stringify.fakearr[i]);
}
There is check for highest ID number sessionID before adding each item from fakearr so this doesn't replace existing sessions when there is hole in IDs (in case of session0, session2, session3. It adds session1 and then continues from session4)