Published on

How to perform callback after login in JavaScript

Authors

Let’s say you’re building a cool e-commerce site which has wish list feature.

When a user who is not logged in but adds a product to wish list, then we need to redirect him to login page.

After he login now we need to add that particular product to his wish list.

If the project follows loosely coupled architecture (API based) then we can easily handle in the client side itself using localStorage.

const isLoggedIn = localStorage.token ? true : false;
// When user clicks add wishlist
const addToWishList = productId => {
  if (!isLoggedIn) {
    localStorage.wishListItem = JSON.stringify({ productId: productId });
    // Redirect to login
    window.location = '/login';
    return;
  }
  // Add that product to wishlist here (Ajax) ?
};

// After the user is successfully authenticated
const loginSuccess = () => {
  if (localStorage.wishListItem) {
    const item = JSON.parse(localStorage.wishListItem);
    addToWishList(item.productId);
    localStorage.removeItem('wishListItem');
  }
};