import { ref, computed, onUnmounted, watch } from 'vue' import { createSWR } from '../../core' import type { Key, Fetcher, SWRConfig as CoreSWRConfig } from '../../core' import type { SWRRefs, SWRRef, SWRConfig } from './types' // Create a basic Vue SWR implementation export function createSWRComposables( key: Key, fetcher: Fetcher, config?: SWRConfig ): SWRRefs { const swr = createSWR({ fetcher, ...config }) const data = ref() const error = ref() const loading = ref(false) const validating = ref(false) // Subscribe to SWR changes const unsubscribe = swr.subscribe(key, (newData, newError, newValidating, newLoading) => { data.value = newData error.value = newError validating.value = newValidating loading.value = newLoading }) // Cleanup on unmount onUnmounted(() => { unsubscribe() }) return { data, error, loading, validating, mutate: (mutateData, options) => swr.mutate(key, mutateData as any, options), revalidate: (options) => swr.revalidate(key, options) } } export function createSWRRef( key: Key, fetcher: Fetcher, config?: SWRConfig ): SWRRef { return createSWRComposables(key, fetcher, config) as SWRRef } // Export individual refs for convenience export const swrDataRef = (key: Key, fetcher: Fetcher, config?: SWRConfig) => createSWRRef(key, fetcher, config).data export const swrErrorRef = (key: Key, fetcher: Fetcher, config?: SWRConfig) => createSWRRef(key, fetcher, config).error export const swrLoadingRef = (key: Key, fetcher: Fetcher, config?: SWRConfig) => createSWRRef(key, fetcher, config).loading export const swrValidatingRef = (key: Key, fetcher: Fetcher, config?: SWRConfig) => createSWRRef(key, fetcher, config).validating // Hook-like function for Vue export function useSWR( key: Key, fetcher: Fetcher, config?: SWRConfig ): SWRRefs { return createSWRComposables(key, fetcher, config) } export function useSWRMutate( key: Key, fetcher: Fetcher, config?: SWRConfig ): SWRRefs { return createSWRComposables(key, fetcher, config) } export function useSWRInstance( key: Key, fetcher: Fetcher, config?: SWRConfig ): SWRRefs { return createSWRComposables(key, fetcher, config) }