On session expire open react dialog in app axios instead of prompt

On session Expire , if any of the API fails then status code comes out to be 401 and we show prompt to ask password and re new the token again . But problem is that we do not want to show prompt we want react dialog to get open instead of that prompt.

Reason of using prompt was that prompt will make the app axios to wait for the password to enter and then it will move forward and will avoid failing of APIs coming next.

We have our code in app.axios file for prompting to ask password on session expire

app.axios.js file is below:-

import axios from "axios";

import store from "../redux/store/store";
import { updateLoaderState } from "../redux/actions/ui-state.action";

import { MESSAGES } from "../constants/messages";
import { APP_PAGES } from "../constants/app-pages";

import UserService from "../services/user.service";
import ClientService from "../services/client.service";
import AuthService from "../services/auth.service";

/**
 * Component is configuring the request and response for axios.
 */
const appAxios = axios.create();

// to maintain the count of api calls, in case of multiple api calls, hide the loader only in case of last call
let activeRequestCount = 0;
// to maintain the promise of getting the new token
let refreshTokenPromise;

/**
 * Configuring the request : Adding JWT token to the request header.
 */
appAxios.interceptors.request.use((req) => {
    // show the loader before any API call
    store.dispatch(updateLoaderState({ showLoader: true }));
    activeRequestCount++;
    const currentUser = UserService.getCurrentUser();
    if (currentUser) {
        req.headers['token'] = currentUser?.token;
    }
    req.headers['app-code'] = ClientService.getAppCode();
    return req;
}, null, { synchronous: true });

/**
 * Configuring the response received
 */
appAxios.interceptors.response.use(
    (res) => {
        activeRequestCount--;
        // hide the loader after getting the response, only if it is the last api call
        if (activeRequestCount === 0) {
            store.dispatch(updateLoaderState({ showLoader: false }));
        }
        return res.data;
    },
    (err) => {
        activeRequestCount = 0;
        store.dispatch(updateLoaderState({ showLoader: false }));
        if (err.response) {
            // if from prompt of session expire , after filling password and hitting login api
            // if any error comes then user is log out
            // error may come in login page while login so we have check for location href also
            // suppose user get error while login again then it will again comes to app axios then
            // we will logout the user so location href check is their as we may get error while logging on login page
            if (err.response.status === 401 && err.config.url.endsWith(APP_PAGES.LOGIN)
                && !window.location.href.endsWith(APP_PAGES.LOGIN)) {
                // If the error originates from the login API and has a status code of 401,
                // logout the user
                AuthService.logout();
            } else if (err.response.status === 401) {
                // For other 401 errors (not from the login API), handle token refresh
                if (!window.location.href.endsWith(APP_PAGES.LOGIN)) {
                    // check for an existing in-progress request
                    if (!refreshTokenPromise) {
                        // if nothing is in-progress, start a new refresh token request
                        // if session got expires then we prompt user for the password
                        // promise is triggered to login after prompt
                        // until the promise resolves other request waits for it
                        const password = prompt(MESSAGES.SESSION_EXPIRED);
                        if (password) {
                            const currentUser = UserService.getCurrentUser();
                            refreshTokenPromise = AuthService.login(currentUser?.email, password)
                                .then(user => {
                                    // clear the promise state
                                    refreshTokenPromise = null;
                                    // resolve the promise with new token
                                    return user?.token;
                                });
                        } else {
                            AuthService.logout();
                        }
                    }

                    // if on cancel of the prompt it is navigated to the login page and log out
                    // then no need for hitting failed request
                    if (!window.location.href.endsWith(APP_PAGES.LOGIN)) {
                        return refreshTokenPromise.then(token => {
                            // since our request gets once failed and also x-csrf token
                            // is reqd to verify if it is from trusted source and not malacious source
                            err.config.headers['X-CSRF-TOKEN'] = token;
                            return appAxios.request(err.config);
                        });
                    }
                }
            }
            return Promise.reject(err);
        }
        throw err;
    }
);

export default appAxios;

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật