Open1
useAspidaSWR拡張案

useConditionalSWR.ts
import useAspidaSWR from '@aspida/swr'
import type { SWRResponse } from 'swr'
// Simple API client interface
interface BaseApiClient {
$get: (option?: Record<string, unknown>) => Promise<unknown>
$path: (option?: Record<string, unknown>) => string
}
// Options type for SWR
type SWROptions = Record<string, unknown>
// Main hook implementation
function useConditionalSWR(
api: BaseApiClient | null,
optionsOrMethod?: string | SWROptions,
options?: SWROptions
): SWRResponse<unknown, Error> {
// Determine if second argument is a method or options
const isMethodCall = typeof optionsOrMethod === 'string'
const method = isMethodCall ? optionsOrMethod : '$get'
const finalOptions = isMethodCall ? options : optionsOrMethod
// Create options that disable fetching when api is null
const swrOptions: SWROptions = {
...(finalOptions && typeof finalOptions === 'object' ? finalOptions : {}),
// Use the new pattern instead of deprecated 'enabled'
key: api === null ? null : undefined,
fetcher: api === null ? null : undefined,
}
// Create a dummy API object when api is null to avoid errors
const safeApi: BaseApiClient = api || {
$get: () => Promise.resolve(null),
$path: () => '',
}
// Always call useAspidaSWR with the same signature to satisfy React Hook rules
// We use method-based call consistently, defaulting to '$get' when no method specified
return useAspidaSWR(safeApi as never, method as never, swrOptions as never)
}
export default useConditionalSWR