Source

src/hooks/useAuth.ts

import axios from "axios";
import { API_URL, reportAxiosError } from "../globals";
import { authStore } from "../stores/AuthStore";

/**
 * Hook that exposes common authentication logic.
 * @category Hooks
 * @namespace useAuth
 */
export const useAuth = () => {
    /**
     * If there is a refresh token available, attempts to use it to obtain a new, valid access token.
     * Used in {@link Atlas}
     * @memberOf useAuth
     */
    const refreshAccessToken = async () => {
        if (authStore.refreshToken) {
            try {
                const tokenData = new URLSearchParams();
                tokenData.append('grant_type', 'refresh_token');
                tokenData.append('refresh_token', authStore.refreshToken);
                tokenData.append('client_id', 'atlas.mobile');
                const { data: refreshResponseData } = await axios.post(API_URL + "/o/token/", tokenData, {
                    headers: { 'Content-Type': "application/x-www-form-urlencoded" }
                });   

                await authStore.setRefreshTokenAsync(refreshResponseData.refresh_token);
                await authStore.setAccessTokenAsync(refreshResponseData.access_token);

                console.info('Successfully refreshed access token, re-attempting initial request...')
            }
            catch (error) {
                reportAxiosError("Error when trying to refresh access token", error);            
            }
        }
    }

    return { refreshAccessToken }
}