I guess I’m posing a silly question, if so thank you for your patience.
In my home.html
I have
JavaScript
x
9
1
<script>
2
document.addEventListener('DOMContentLoaded', function() {
3
[ ]
4
var taskObj = {};
5
localStorage.setItem('task_object', JSON.stringify(taskObj));
6
[ ]
7
}
8
</script>
9
In another_page.html
JavaScript
1
10
10
1
<script>
2
document.addEventListener('DOMContentLoaded', function() {
3
[ ]
4
var taskObj_a = JSON.parse(localStorage.getItem('task_object') || '{}');
5
taskObj_a.name = "a new task";
6
localStorage.setItem('task_object', JSON.stringify(taskObj_a));
7
[ ]
8
}
9
</script>
10
When the user is redirected to home.html, the taskObj gets initialised again and I lose the “name” property set in another_page.html
.
How can I avoid this and do not reset the taskObj
?
Thank you for any help you can provide.
Advertisement
Answer
You can check if the item already exists in local storage and only set it if it doesnt.
JavaScript
1
2
1
if(!localStorage.getItem('task_object')) localStorage.setItem('{}')
2