The auth logic is implemented and encapsulated in the AuthProvider and can be accessed using the useAuth() hook. We can invoke the useAuth() from either another hook or a functional component. But I need to access its two functions, namely getAccessToken and refreshAccessToken from a JS module named axios.ts that has nothing to with React. How can this be done?
// AuthProvider.ts
export const AuthProvider: React.FC = ({ children }) => {
//useState to set the local state in this component.
login();
logout();
getAccessToken(); <------ get the access token from the local storage
refreshAccessToken();
}
export const useAuth = () => useContext(AuthContext);
Note that refreshAccessToken() is setting the local state in the AuthProvider component and making a call to an api endpoint to refresh the token.
Based on the answer given in this post, I created a separated module to register axios interceptors (instead of registering them in a React component) so that they are loaded only once.
axios-auth-refresh is a stable third-party module to intercept the requests and add authorization header to them and also makes calls to the refreshToken endpoint.
// axios.ts
import createAuthRefreshInterceptor from "axios-auth-refresh";
const axiosApiInstance = axios.create({
baseURL: apiEndipoint,
});
axiosApiInstance.interceptors.request.use((request) => {
// Inject the token in request header
if (getAccessToken()) { <---- cannot access getAccessToken because React does not allow to
use the hooks in plain JS files
request.headers.Authorization = `Bearer ${getAccessToken()}`,
}
return request;
});
createAuthRefreshInterceptor(
axiosApiInstance,
refreshAccessToken, <---- for the same reason, cannot obtain a reference
to the refreshAccessToken defined in AuthProvider
axiosAuthRefreshOptions
);
I need to access the getToken() and refreshAccessToken() in axios.ts to make it work. getToken() simply returns the token from the local storage and thus, as a workaround, I can access the local storage directly in the axios.ts.
But how to access refreshAccessToken, pl. guide.