import useSWR, { type SWRConfiguration } from 'swr' import { useSession } from 'next-auth/react'; import { type ResponseData } from '@/types/types'; import useAxiosAuth from './useAxiosAuth'; export default function useFetch(endpoint: string) { const BASE_URL = process.env.BASE_URL_API const { data: session } = useSession() const fetcher = (endpoint: string) => fetch(BASE_URL + endpoint, { headers: { Authorization: `Bearer ${session?.user.access_token}`, } }).then(res => res.json()) const { data, error, isLoading, mutate } = useSWR>(endpoint, fetcher) return { data: data?.data, isLoading, error, mutate } } export function useFetchWithAxios(url: string | null, options?: SWRConfiguration) { const axios = useAxiosAuth(); // Only define fetcher if url is present const fetcher = (url: string) => axios.get(url).then(res => res.data) // Pass url directly. If it is null, SWR will pause. const { data, error, isLoading, mutate } = useSWR>(url, fetcher, options) return { data: data?.data, isLoading, error, mutate } } export function useFetchPOSTWithAxios(endpointKey: [string, ...any[]] | null, payload: any = {}, options?: SWRConfiguration) { const axios = useAxiosAuth(); const fetcher = ([url, ..._]: [string, ...any[]]) => axios.post(url, payload).then(res => res.data); const { data, error, isLoading, mutate } = useSWR( endpointKey, // Keep it as an array for SWR to track fetcher, options ); return { data: data?.data, isLoading, error, mutate }; }