fix: 🐛 session (#2174)

fixed session refresh error

# Description

Please include a summary of the changes and the related issue. Please
also include relevant motivation and context.

## Checklist before requesting a review

Please delete options that are not relevant.

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my code
- [ ] I have commented hard-to-understand areas
- [ ] I have ideally added tests that prove my fix is effective or that
my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged

## Screenshots (if appropriate):
This commit is contained in:
Stan Girard 2024-02-09 23:52:24 -08:00 committed by GitHub
parent 0f398a0452
commit e29d7483c4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,4 +1,8 @@
import axios, { AxiosError, AxiosInstance } from "axios";
import axios, {
AxiosError,
AxiosInstance,
InternalAxiosRequestConfig,
} from "axios";
import { useSupabase } from "@/lib/context/SupabaseProvider";
@ -9,17 +13,34 @@ const axiosInstance = axios.create({
});
export const useAxios = (): { axiosInstance: AxiosInstance } => {
const { session } = useSupabase();
let { session } = useSupabase();
const { supabase } = useSupabase();
axiosInstance.interceptors.request.clear();
axiosInstance.interceptors.request.use(
(config) => {
config.headers["Authorization"] = `Bearer ${session?.access_token ?? ""}`;
async (value: InternalAxiosRequestConfig) => {
// Check if the session is valid
if (
session &&
session.expires_at &&
session.expires_at * 1000 < Date.now()
) {
// If the session is not valid, refresh it
const { data, error } = await supabase.auth.refreshSession();
if (error) {
throw error;
}
session = data?.session;
}
return config;
value.headers = value.headers || {};
value.headers["Authorization"] = `Bearer ${session?.access_token ?? ""}`;
return value;
},
(error: AxiosError) => {
console.error({ error });
void Promise.reject(error);
return Promise.reject(error);
}
);