How to keep localStorage values after refresh?

42,619

Solution 1

Your line $window.localStorage.setItem('initData', JSON.stringify($scope.initData)); is resetting the data each time you refresh.

Replace the line with this:

if(!localStorage.getItem('initData')){
    $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}

More over you should not have that line at all. Start with an empty local storage and add new entries from UI only.

The above code only run it once, for the first time the application is run.

If yo want to re-insert the data every time the list is empty then try following

if(!localStorage.getItem('initData') || JSON.parse(localStorage.getItem('initData')).length === 0){
    $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}

Solution 2

On every page load you are setting new initData and updating the local storage... Instead you should check for existing localstorage data and use that before using the mocked initData

Solution 3

I was facing the same issue for months. And finally I found the solution. ( I am not sure whether this is the same problem for you, anyway sharing my scenario )

When I was testing on my local host, I was using the URL as http://localhost:3000/ for loading the page. But during login, after page refresh, I was using actually the IP address to redirect the page, which was like http://192.163.1.31:3000/.

So the result, the local storage of http://localhost:3000/ contains the values I saved, but the local storage of http://192.163.1.31:3000/ doesn't contain the values I saved.

So I fixed the solution by simply using same URL across the launch till page load. And the problem was fixed. ( I used http://192.163.1.31:3000/ instead of http://localhost:3000/)

For your case, check whether the URL is different after the page reload.If yes, fix it, and your problem may not persist

Solution 4

You need to check first if your localStorage is empty on load

if (localStorage == null) {//setItem() ...};

Solution 5

delete data from local storage using JavaScript Here is your code without error passed.

use function for delete

       function deleteRow(index){
              dataList.splice(index, 1);
              console.log('====>', dataList)
              localStorage.setItem('items', JSON.stringify(dataList)); 
}
Share:
42,619
tholo
Author by

tholo

Updated on July 28, 2022

Comments

  • tholo
    tholo almost 2 years

    This is my ctrl:

    app.controller('ctrl', function ($window, $scope) {
    
        $scope.initData = [
            {
                firstName: "John",
                lastName: "Doe",  
            },
            {
                firstName: "Jane",
                lastName: "Doe",
            },
            {
                firstName: "John",
                lastName: "Smith",
            }
        ];
    
        $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
        $scope.retrievedData = JSON.parse($window.localStorage.getItem('initData'));
        $scope.sortedType = 'firstName';
        $scope.sortedReverse = false;
        //Remove Rows and Update localStorage Key Values
        $scope.removeRow = function(row) {
            $scope.retrievedData.splice(row, 1);
            $scope.initData.splice(row, 1);
            $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
        }
    });
    

    HTML:

    <table class="table table-bordered table-striped table-hover">
                    <thead>
                    <tr>
                        <th>
                            <span ng-show="sortedType == 'firstName' && sortedReverse" class="fa fa-long-arrow-up"></span>
                            <span ng-show="sortedType == 'firstName' && !sortedReverse" class="fa fa-long-arrow-down"></span>
                            <span href="#" ng-click="sortedType = 'firstName'; sortedReverse = !sortedReverse" style="cursor:pointer;">First Name</span>
                        </th>
                        <th>
                            <span ng-show="sortedType == 'lastName' && sortedReverse" class="fa fa-long-arrow-up"></span>
                            <span ng-show="sortedType == 'lastName' && !sortedReverse" class="fa fa-long-arrow-down"></span>
                            <span href="#" ng-click="sortedType = 'lastName'; sortedReverse = !sortedReverse" style="cursor:pointer;">Last Name</span>
                        </th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="(k, v) in retrievedData | orderBy: sortedType: sortedReverse">
                    <td>{{v.firstName}}</td>
                    <td>{{v.lastName}}</td>
                    <td>
                        <button class="btn btn-primary">Edit</button>
                        <button class="btn btn-primary" ng-click="removeRow();">Delete</button>
                    </td>
                </tr>
                </tbody>
            </table>
    

    Now, I believe it is clear what this does. It is assigning a data from $scope.initData to localStorage and then interpolate it into the HTML. the function removeRow() deletes the row in the table and updates the localStorage with the latest action. The issue with this is that each time I reload the HTML the initial localStorage data gets loaded and not the updated one. I know that this is because I'm assigning it here: $window.localStorage.setItem('initData', JSON.stringify($scope.initData)); but I don't know how to keep it updated after the refresh.

    Please advise.

    Thanks.

  • tholo
    tholo almost 7 years
    I should have this line.. I need to have some initial data, hence the line. :)
  • BiJ
    BiJ almost 7 years
    Then you should add the conditional check to see if there is no data then only insert.
  • tholo
    tholo almost 7 years
    You mean if (localStorage == null) {}; ? :)
  • Jonathan
    Jonathan almost 7 years
    yes ! sorry typo; check if your localoStorage is not empty , if it is empty than you can setItem
  • tholo
    tholo almost 7 years
    are you still here? There is an issue with this.
  • tholo
    tholo almost 7 years
    An interesting one.. Your answer is not quite correct, since there is a still key 'initData' only an empty array is a value, that is if all is deleted :)
  • BiJ
    BiJ almost 7 years
    yes it will only insert for the first time the application is run. Afterwards when the user clears everything manually from the UI (makes the list empty), I dont think we should re insert the data.
  • tholo
    tholo almost 7 years
    I'm there, waiting for you.
  • BiJ
    BiJ almost 7 years
    Cant join chat, blocked by firewall. I have updated the ans to solve your issue.
  • tholo
    tholo almost 7 years
    the issue is when an action is repeated. It's only working on the first delete...
  • tholo
    tholo almost 7 years
    Nope, it doesn't work. When I delete it multiple times on refresh the rows are added. If I empty, they are added. Always following the same pattern: delete 3 - 4 are added, delete 2 - 3 are added, delete all - 2 are added
  • Goyani un
    Goyani un almost 6 years
    its easiest to understand dataList is array here in this my object is pushed
  • Goyani un
    Goyani un almost 6 years
    items is key name(databaseName)