How to perform callback after login in JavaScript

June 14, 2017

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.

product wishlist

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';
  // Add that product to wishlist here (Ajax) ?

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

👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP