Reputation: 3080
I am trying to keep some data in sessionStorage, but if I refresh the page or leave from a link then come back, the sessionStorage no longer exists.
I am new to sessionStorage, so sorry if this is an obvious fix.
Essentially I store an array into the sessionStorage.
$scope.addPlant = function(plant) {
for (i = 0; i < $scope.userPlantList.length; i++) {
if ($scope.userPlantList[i] === plant) {
alert("You have already added this plant");
return;
}
}
$scope.userPlantList.push($scope.currentPlant);
sessionStorage.setItem("Plants",JSON.stringify($scope.userPlantList));
};
And then when I want to see what is all stored
$scope.retreiveList = function() {
var retrieved = sessionStorage.getItem("Plants");
$scope.userPlantList = JSON.parse(retrieved);
}
And this works fine when I do not refresh the page/app at all.
Question: How can I get my sessionStorage to last during a refresh/immediate re-visit?
Upvotes: 9
Views: 32699
Reputation: 21506
If you have devtools open, Chromium (at least version 124) seems to have a bug where if you do something like:
btn.onclick = () => {
sessionStorage.test = 'x';
location.reload();
}
It will not save your test-key. Just spent way too long figuring that out. Much frustrate.
The bad solution is to close devtools and hope you and your users don't have it open when clicking that button.
Upvotes: 0
Reputation: 18059
I would recommend using the $window
provider from angular
// set
$window.sessionStorage.setItem('Plants', angular.toJson($scope.userPlantList));
// get
$scope.userPlantList = angular.fromJson($window.sessionStorage.getItem('Plants')) || [];
Upvotes: 1
Reputation: 788
Check if the data are really gone by looking at the developer tools
If you using chrome: F12 -> Resources tab -> Session Storage.
sessionStorage lives with the browser tab. whenever you close a tab the sessionstorage data will be wiped out.
if you want something that will be shared across tabs, look for localStorage.
Upvotes: 11