Persisting state across page reloads using localStorage

Loading

In AngularJS, application state is typically stored in services or $scope, but this state is lost when the page is reloaded. To persist data across page reloads, we can use localStorage, which allows us to store data in the browser permanently (until manually cleared).


What is localStorage?

  • Key-Value Storage: Stores data as key-value pairs.
  • Persistent: Data remains even after the page is refreshed or the browser is closed.
  • Supports Strings Only: Can store only string data, so objects must be converted to JSON (JSON.stringify()).
  • Limited Size: Typically around 5MB per domain.

Steps to Persist State Using localStorage

  1. Create an AngularJS service to manage state.
  2. Store data in localStorage whenever it changes.
  3. Retrieve stored data when the application initializes.
  4. Use the service in controllers for state management.

Example: Persisting User Session Data

Step 1: Create a Service for Managing State

We create a UserService that interacts with localStorage.

app.factory('UserService', function() {
var userKey = 'user_data'; // Key for localStorage

return {
// Get user data from localStorage
getUser: function() {
var user = localStorage.getItem(userKey);
return user ? JSON.parse(user) : null;
},

// Save user data to localStorage
setUser: function(user) {
localStorage.setItem(userKey, JSON.stringify(user));
},

// Clear user data
clearUser: function() {
localStorage.removeItem(userKey);
}
};
});

What this service does:

  • getUser(): Retrieves user data from localStorage and converts it back to an object.
  • setUser(): Saves user data by converting it into a JSON string.
  • clearUser(): Removes user data from localStorage.

Step 2: Use the Service in a Controller

We now use UserService inside a controller to manage user data.

app.controller('UserController', function($scope, UserService) {
// Initialize user from localStorage
$scope.user = UserService.getUser() || { name: '', email: '' };

// Save user data when changed
$scope.saveUser = function() {
UserService.setUser($scope.user);
alert('User data saved!');
};

// Clear user data
$scope.logout = function() {
UserService.clearUser();
$scope.user = { name: '', email: '' };
alert('User data cleared!');
};
});

How it works:

  • The $scope.user is initialized from localStorage when the controller loads.
  • When the user updates their data, saveUser() stores it in localStorage.
  • The logout() function clears the saved user data.

Step 3: HTML UI for User Input

<div ng-controller="UserController">
<label>Name:</label>
<input type="text" ng-model="user.name">

<label>Email:</label>
<input type="email" ng-model="user.email">

<button ng-click="saveUser()">Save</button>
<button ng-click="logout()">Logout</button>
</div>

Behavior:

  • The user’s data remains even after a page refresh.
  • Clicking “Logout” clears the data from both UI and localStorage.

Persisting Complex Application State

If you need to persist multiple state variables, you can create a StateService:

app.factory('StateService', function() {
return {
saveState: function(key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
getState: function(key) {
var data = localStorage.getItem(key);
return data ? JSON.parse(data) : null;
},
clearState: function(key) {
localStorage.removeItem(key);
}
};
});

Usage in a Controller:

app.controller('CartController', function($scope, StateService) {
$scope.cart = StateService.getState('cart') || [];

$scope.addItem = function(item) {
$scope.cart.push(item);
StateService.saveState('cart', $scope.cart);
};

$scope.clearCart = function() {
StateService.clearState('cart');
$scope.cart = [];
};
});

This allows:

  • Persisting shopping cart data across page reloads.
  • Preventing data loss in case of browser refresh.

Handling sessionStorage (Temporary Storage)

If you want data to persist only for the session (until the tab is closed), use sessionStorage instead.

sessionStorage.setItem('key', 'value'); // Store
var value = sessionStorage.getItem('key'); // Retrieve
sessionStorage.removeItem('key'); // Remove

Performance Considerations

Best Practices for Using localStorage:

  • Avoid storing large objects (limit to essential data).
  • Use JSON compression for complex objects (e.g., LZString.compressToUTF16()).
  • Always handle errors in case localStorage is disabled.
  • Use services to centralize localStorage interactions.

Leave a Reply

Your email address will not be published. Required fields are marked *