@fluxbase/sdk-react
Version:
React hooks for Fluxbase SDK
607 lines (594 loc) • 19.6 kB
TypeScript
import * as react_jsx_runtime from 'react/jsx-runtime';
import { ReactNode } from 'react';
import * as _fluxbase_sdk from '@fluxbase/sdk';
import { FluxbaseClient, User, AuthSession, SignInCredentials, SignUpCredentials, QueryBuilder, RealtimeCallback, RealtimeChangePayload, ListOptions, UploadOptions, AdminAuthResponse, ListUsersOptions, EnrichedUser, APIKey, CreateAPIKeyRequest, Webhook, CreateWebhookRequest, UpdateWebhookRequest, AppSettings, UpdateAppSettingsRequest, SystemSetting, UpdateSystemSettingRequest } from '@fluxbase/sdk';
export { APIKey, AdminUser, AppSettings, AuthSession, EnrichedUser, FluxbaseClient, PostgrestResponse, RealtimeChangePayload, SignInCredentials, SignUpCredentials, StorageObject, SystemSetting, User, Webhook } from '@fluxbase/sdk';
import * as _tanstack_react_query from '@tanstack/react-query';
import { UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';
import * as _tanstack_query_core from '@tanstack/query-core';
interface FluxbaseProviderProps {
client: FluxbaseClient;
children: ReactNode;
}
/**
* Provider component to make Fluxbase client available throughout the app
*/
declare function FluxbaseProvider({ client, children }: FluxbaseProviderProps): react_jsx_runtime.JSX.Element;
/**
* Hook to access the Fluxbase client from context
*/
declare function useFluxbaseClient(): FluxbaseClient;
/**
* Hook to get the current user
*/
declare function useUser(): _tanstack_react_query.UseQueryResult<User | null, Error>;
/**
* Hook to get the current session
*/
declare function useSession(): _tanstack_react_query.UseQueryResult<AuthSession | null, Error>;
/**
* Hook for signing in
*/
declare function useSignIn(): _tanstack_react_query.UseMutationResult<AuthSession | _fluxbase_sdk.SignInWith2FAResponse, Error, SignInCredentials, unknown>;
/**
* Hook for signing up
*/
declare function useSignUp(): _tanstack_react_query.UseMutationResult<AuthSession, Error, SignUpCredentials, unknown>;
/**
* Hook for signing out
*/
declare function useSignOut(): _tanstack_react_query.UseMutationResult<void, Error, void, unknown>;
/**
* Hook for updating the current user
*/
declare function useUpdateUser(): _tanstack_react_query.UseMutationResult<User, Error, Partial<Pick<User, "email" | "metadata">>, unknown>;
/**
* Combined auth hook with all auth state and methods
*/
declare function useAuth(): {
user: User | null | undefined;
session: AuthSession | null | undefined;
isLoading: boolean;
isAuthenticated: boolean;
signIn: _tanstack_react_query.UseMutateAsyncFunction<AuthSession | _fluxbase_sdk.SignInWith2FAResponse, Error, SignInCredentials, unknown>;
signUp: _tanstack_react_query.UseMutateAsyncFunction<AuthSession, Error, SignUpCredentials, unknown>;
signOut: _tanstack_react_query.UseMutateAsyncFunction<void, Error, void, unknown>;
updateUser: _tanstack_react_query.UseMutateAsyncFunction<User, Error, Partial<Pick<User, "email" | "metadata">>, unknown>;
isSigningIn: boolean;
isSigningUp: boolean;
isSigningOut: boolean;
isUpdating: boolean;
};
interface UseFluxbaseQueryOptions<T> extends Omit<UseQueryOptions<T[], Error>, 'queryKey' | 'queryFn'> {
/**
* Custom query key. If not provided, will use table name and filters.
*/
queryKey?: unknown[];
}
/**
* Hook to execute a database query
* @param buildQuery - Function that builds and returns the query
* @param options - React Query options
*/
declare function useFluxbaseQuery<T = any>(buildQuery: (client: ReturnType<typeof useFluxbaseClient>) => QueryBuilder<T>, options?: UseFluxbaseQueryOptions<T>): _tanstack_react_query.UseQueryResult<T[], Error>;
/**
* Hook for table queries with a simpler API
* @param table - Table name
* @param buildQuery - Function to build the query
*/
declare function useTable<T = any>(table: string, buildQuery?: (query: QueryBuilder<T>) => QueryBuilder<T>, options?: UseFluxbaseQueryOptions<T>): _tanstack_react_query.UseQueryResult<T[], Error>;
/**
* Hook to insert data into a table
*/
declare function useInsert<T = any>(table: string): _tanstack_react_query.UseMutationResult<T | null, Error, Partial<T> | Partial<T>[], unknown>;
/**
* Hook to update data in a table
*/
declare function useUpdate<T = any>(table: string): _tanstack_react_query.UseMutationResult<T | null, Error, {
data: Partial<T>;
buildQuery: (query: QueryBuilder<T>) => QueryBuilder<T>;
}, unknown>;
/**
* Hook to upsert data into a table
*/
declare function useUpsert<T = any>(table: string): _tanstack_react_query.UseMutationResult<T | null, Error, Partial<T> | Partial<T>[], unknown>;
/**
* Hook to delete data from a table
*/
declare function useDelete<T = any>(table: string): _tanstack_react_query.UseMutationResult<void, Error, (query: QueryBuilder<T>) => QueryBuilder<T>, unknown>;
interface UseRealtimeOptions {
/**
* The channel name (e.g., 'table:public.products')
*/
channel: string;
/**
* Event type to listen for ('INSERT', 'UPDATE', 'DELETE', or '*' for all)
*/
event?: 'INSERT' | 'UPDATE' | 'DELETE' | '*';
/**
* Callback function when an event is received
*/
callback?: RealtimeCallback;
/**
* Whether to automatically invalidate queries for the table
* Default: true
*/
autoInvalidate?: boolean;
/**
* Custom query key to invalidate (if autoInvalidate is true)
* Default: ['fluxbase', 'table', tableName]
*/
invalidateKey?: unknown[];
/**
* Whether the subscription is enabled
* Default: true
*/
enabled?: boolean;
}
/**
* Hook to subscribe to realtime changes for a channel
*/
declare function useRealtime(options: UseRealtimeOptions): {
channel: _fluxbase_sdk.RealtimeChannel | null;
};
/**
* Hook to subscribe to a table's changes
* @param table - Table name (with optional schema, e.g., 'public.products')
* @param options - Subscription options
*/
declare function useTableSubscription(table: string, options?: Omit<UseRealtimeOptions, 'channel'>): {
channel: _fluxbase_sdk.RealtimeChannel | null;
};
/**
* Hook to subscribe to INSERT events on a table
*/
declare function useTableInserts(table: string, callback: (payload: RealtimeChangePayload) => void, options?: Omit<UseRealtimeOptions, 'channel' | 'event' | 'callback'>): {
channel: _fluxbase_sdk.RealtimeChannel | null;
};
/**
* Hook to subscribe to UPDATE events on a table
*/
declare function useTableUpdates(table: string, callback: (payload: RealtimeChangePayload) => void, options?: Omit<UseRealtimeOptions, 'channel' | 'event' | 'callback'>): {
channel: _fluxbase_sdk.RealtimeChannel | null;
};
/**
* Hook to subscribe to DELETE events on a table
*/
declare function useTableDeletes(table: string, callback: (payload: RealtimeChangePayload) => void, options?: Omit<UseRealtimeOptions, 'channel' | 'event' | 'callback'>): {
channel: _fluxbase_sdk.RealtimeChannel | null;
};
/**
* Hook to list files in a bucket
*/
declare function useStorageList(bucket: string, options?: ListOptions & Omit<UseQueryOptions<any[], Error>, 'queryKey' | 'queryFn'>): _tanstack_react_query.UseQueryResult<any[], Error>;
/**
* Hook to upload a file to a bucket
*/
declare function useStorageUpload(bucket: string): _tanstack_react_query.UseMutationResult<_fluxbase_sdk.StorageObject | null, Error, {
path: string;
file: File | Blob | ArrayBuffer;
options?: UploadOptions;
}, unknown>;
/**
* Hook to download a file from a bucket
*/
declare function useStorageDownload(bucket: string, path: string | null, enabled?: boolean): _tanstack_react_query.UseQueryResult<Blob | null, Error>;
/**
* Hook to delete files from a bucket
*/
declare function useStorageDelete(bucket: string): _tanstack_react_query.UseMutationResult<void, Error, string[], unknown>;
/**
* Hook to get a public URL for a file
*/
declare function useStoragePublicUrl(bucket: string, path: string | null): string | null;
/**
* Hook to create a signed URL
*/
declare function useStorageSignedUrl(bucket: string, path: string | null, expiresIn?: number): _tanstack_react_query.UseQueryResult<string | null, Error>;
/**
* Hook to move a file
*/
declare function useStorageMove(bucket: string): _tanstack_react_query.UseMutationResult<_fluxbase_sdk.StorageObject | null, Error, {
fromPath: string;
toPath: string;
}, unknown>;
/**
* Hook to copy a file
*/
declare function useStorageCopy(bucket: string): _tanstack_react_query.UseMutationResult<_fluxbase_sdk.StorageObject | null, Error, {
fromPath: string;
toPath: string;
}, unknown>;
/**
* Hook to manage buckets
*/
declare function useStorageBuckets(): _tanstack_react_query.UseQueryResult<{
name: string;
created_at: string;
}[], Error>;
/**
* Hook to create a bucket
*/
declare function useCreateBucket(): _tanstack_react_query.UseMutationResult<void, Error, string, unknown>;
/**
* Hook to delete a bucket
*/
declare function useDeleteBucket(): _tanstack_react_query.UseMutationResult<void, Error, string, unknown>;
/**
* Hook to call a PostgreSQL function and cache the result
*
* @example
* ```tsx
* const { data, isLoading, error } = useRPC(
* 'calculate_total',
* { order_id: 123 },
* { enabled: !!orderId }
* )
* ```
*/
declare function useRPC<TData = unknown, TParams extends Record<string, unknown> = Record<string, unknown>>(functionName: string, params?: TParams, options?: Omit<UseQueryOptions<TData, Error>, 'queryKey' | 'queryFn'>): _tanstack_react_query.UseQueryResult<_tanstack_query_core.NoInfer<TData>, Error>;
/**
* Hook to create a mutation for calling PostgreSQL functions
* Useful for functions that modify data
*
* @example
* ```tsx
* const createOrder = useRPCMutation('create_order')
*
* const handleSubmit = async () => {
* await createOrder.mutateAsync({
* user_id: 123,
* items: [{ product_id: 1, quantity: 2 }]
* })
* }
* ```
*/
declare function useRPCMutation<TData = unknown, TParams extends Record<string, unknown> = Record<string, unknown>>(functionName: string, options?: Omit<UseMutationOptions<TData, Error, TParams>, 'mutationFn'>): _tanstack_react_query.UseMutationResult<TData, Error, TParams, unknown>;
/**
* Hook to call multiple RPC functions in parallel
*
* @example
* ```tsx
* const { data, isLoading } = useRPCBatch([
* { name: 'get_user_stats', params: { user_id: 123 } },
* { name: 'get_recent_orders', params: { limit: 10 } },
* ])
* ```
*/
declare function useRPCBatch<TData = unknown>(calls: Array<{
name: string;
params?: Record<string, unknown>;
}>, options?: Omit<UseQueryOptions<TData[], Error, TData[], readonly unknown[]>, 'queryKey' | 'queryFn'>): _tanstack_react_query.UseQueryResult<TData[], Error>;
/**
* Simplified admin user type returned by authentication
*/
interface AdminUser {
id: string;
email: string;
role: string;
}
interface UseAdminAuthOptions {
/**
* Automatically check authentication status on mount
* @default true
*/
autoCheck?: boolean;
}
interface UseAdminAuthReturn {
/**
* Current admin user if authenticated
*/
user: AdminUser | null;
/**
* Whether the admin is authenticated
*/
isAuthenticated: boolean;
/**
* Whether the authentication check is in progress
*/
isLoading: boolean;
/**
* Any error that occurred during authentication
*/
error: Error | null;
/**
* Login as admin
*/
login: (email: string, password: string) => Promise<AdminAuthResponse>;
/**
* Logout admin
*/
logout: () => Promise<void>;
/**
* Refresh admin user info
*/
refresh: () => Promise<void>;
}
/**
* Hook for admin authentication
*
* Manages admin login state, authentication checks, and user info.
*
* @example
* ```tsx
* function AdminLogin() {
* const { user, isAuthenticated, isLoading, login, logout } = useAdminAuth()
*
* const handleLogin = async (e: React.FormEvent) => {
* e.preventDefault()
* await login(email, password)
* }
*
* if (isLoading) return <div>Loading...</div>
* if (isAuthenticated) return <div>Welcome {user?.email}</div>
*
* return <form onSubmit={handleLogin}>...</form>
* }
* ```
*/
declare function useAdminAuth(options?: UseAdminAuthOptions): UseAdminAuthReturn;
interface UseUsersOptions extends ListUsersOptions {
/**
* Whether to automatically fetch users on mount
* @default true
*/
autoFetch?: boolean;
/**
* Refetch interval in milliseconds (0 to disable)
* @default 0
*/
refetchInterval?: number;
}
interface UseUsersReturn {
/**
* Array of users
*/
users: EnrichedUser[];
/**
* Total number of users (for pagination)
*/
total: number;
/**
* Whether users are being fetched
*/
isLoading: boolean;
/**
* Any error that occurred
*/
error: Error | null;
/**
* Refetch users
*/
refetch: () => Promise<void>;
/**
* Invite a new user
*/
inviteUser: (email: string, role: 'user' | 'admin') => Promise<void>;
/**
* Update user role
*/
updateUserRole: (userId: string, role: 'user' | 'admin') => Promise<void>;
/**
* Delete a user
*/
deleteUser: (userId: string) => Promise<void>;
/**
* Reset user password
*/
resetPassword: (userId: string) => Promise<{
message: string;
}>;
}
/**
* Hook for managing users
*
* Provides user list with pagination, search, and management functions.
*
* @example
* ```tsx
* function UserList() {
* const { users, total, isLoading, refetch, inviteUser, deleteUser } = useUsers({
* limit: 20,
* search: searchTerm
* })
*
* return (
* <div>
* {isLoading ? <Spinner /> : (
* <ul>
* {users.map(user => (
* <li key={user.id}>
* {user.email} - {user.role}
* <button onClick={() => deleteUser(user.id)}>Delete</button>
* </li>
* ))}
* </ul>
* )}
* </div>
* )
* }
* ```
*/
declare function useUsers(options?: UseUsersOptions): UseUsersReturn;
interface UseAPIKeysOptions {
/**
* Whether to automatically fetch API keys on mount
* @default true
*/
autoFetch?: boolean;
}
interface UseAPIKeysReturn {
/**
* Array of API keys
*/
keys: APIKey[];
/**
* Whether keys are being fetched
*/
isLoading: boolean;
/**
* Any error that occurred
*/
error: Error | null;
/**
* Refetch API keys
*/
refetch: () => Promise<void>;
/**
* Create a new API key
*/
createKey: (request: CreateAPIKeyRequest) => Promise<{
key: string;
keyData: APIKey;
}>;
/**
* Update an API key
*/
updateKey: (keyId: string, update: {
name?: string;
description?: string;
}) => Promise<void>;
/**
* Revoke an API key
*/
revokeKey: (keyId: string) => Promise<void>;
/**
* Delete an API key
*/
deleteKey: (keyId: string) => Promise<void>;
}
/**
* Hook for managing API keys
*
* Provides API key list and management functions.
*
* @example
* ```tsx
* function APIKeyManager() {
* const { keys, isLoading, createKey, revokeKey } = useAPIKeys()
*
* const handleCreate = async () => {
* const { key, keyData } = await createKey({
* name: 'Backend Service',
* description: 'API key for backend',
* expires_at: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString()
* })
* alert(`Key created: ${key}`)
* }
*
* return (
* <div>
* <button onClick={handleCreate}>Create Key</button>
* {keys.map(k => (
* <div key={k.id}>
* {k.name}
* <button onClick={() => revokeKey(k.id)}>Revoke</button>
* </div>
* ))}
* </div>
* )
* }
* ```
*/
declare function useAPIKeys(options?: UseAPIKeysOptions): UseAPIKeysReturn;
/**
* Admin Settings and Management Hooks
*
* Hooks for managing application settings, system settings, and webhooks.
*/
interface UseAppSettingsOptions {
autoFetch?: boolean;
}
interface UseAppSettingsReturn {
settings: AppSettings | null;
isLoading: boolean;
error: Error | null;
refetch: () => Promise<void>;
updateSettings: (update: UpdateAppSettingsRequest) => Promise<void>;
}
/**
* Hook for managing application settings
*
* @example
* ```tsx
* function SettingsPanel() {
* const { settings, isLoading, updateSettings } = useAppSettings({ autoFetch: true })
*
* const handleToggleFeature = async (feature: string, enabled: boolean) => {
* await updateSettings({
* features: { ...settings?.features, [feature]: enabled }
* })
* }
*
* return <div>...</div>
* }
* ```
*/
declare function useAppSettings(options?: UseAppSettingsOptions): UseAppSettingsReturn;
interface UseSystemSettingsOptions {
autoFetch?: boolean;
}
interface UseSystemSettingsReturn {
settings: SystemSetting[];
isLoading: boolean;
error: Error | null;
refetch: () => Promise<void>;
getSetting: (key: string) => SystemSetting | undefined;
updateSetting: (key: string, update: UpdateSystemSettingRequest) => Promise<void>;
deleteSetting: (key: string) => Promise<void>;
}
/**
* Hook for managing system settings (key-value storage)
*
* @example
* ```tsx
* function SystemSettings() {
* const { settings, isLoading, updateSetting } = useSystemSettings({ autoFetch: true })
*
* const handleUpdateSetting = async (key: string, value: any) => {
* await updateSetting(key, { value })
* }
*
* return <div>...</div>
* }
* ```
*/
declare function useSystemSettings(options?: UseSystemSettingsOptions): UseSystemSettingsReturn;
interface UseWebhooksOptions {
autoFetch?: boolean;
refetchInterval?: number;
}
interface UseWebhooksReturn {
webhooks: Webhook[];
isLoading: boolean;
error: Error | null;
refetch: () => Promise<void>;
createWebhook: (webhook: CreateWebhookRequest) => Promise<Webhook>;
updateWebhook: (id: string, update: UpdateWebhookRequest) => Promise<Webhook>;
deleteWebhook: (id: string) => Promise<void>;
testWebhook: (id: string) => Promise<void>;
}
/**
* Hook for managing webhooks
*
* @example
* ```tsx
* function WebhooksManager() {
* const { webhooks, isLoading, createWebhook, deleteWebhook } = useWebhooks({
* autoFetch: true
* })
*
* const handleCreate = async () => {
* await createWebhook({
* url: 'https://example.com/webhook',
* events: ['user.created', 'user.updated'],
* enabled: true
* })
* }
*
* return <div>...</div>
* }
* ```
*/
declare function useWebhooks(options?: UseWebhooksOptions): UseWebhooksReturn;
export { FluxbaseProvider, useAPIKeys, useAdminAuth, useAppSettings, useAuth, useCreateBucket, useDelete, useDeleteBucket, useFluxbaseClient, useFluxbaseQuery, useInsert, useRPC, useRPCBatch, useRPCMutation, useRealtime, useSession, useSignIn, useSignOut, useSignUp, useStorageBuckets, useStorageCopy, useStorageDelete, useStorageDownload, useStorageList, useStorageMove, useStoragePublicUrl, useStorageSignedUrl, useStorageUpload, useSystemSettings, useTable, useTableDeletes, useTableInserts, useTableSubscription, useTableUpdates, useUpdate, useUpdateUser, useUpsert, useUser, useUsers, useWebhooks };