@bluecopa/react
v0.1.38
Published
Bluecopa react library with TanStack Query integration
Downloads
512
Maintainers
Readme
@bluecopa/react

A Comprehensive React Query Integration for Bluecopa
A React library providing opinionated custom hooks for TanStack React Query integration with Bluecopa core API. This package enables efficient data fetching, caching, and synchronization with the Bluecopa platform while maintaining type safety and developer experience.
Table of Contents
- @bluecopa/react
- A Comprehensive React Query Integration for Bluecopa
- Table of Contents
- Features
- Installation
- Usage
- API Documentation
useUser(options?)useDataset(datasetId, options?)useDatasetSample(datasetId, options?)useMetric(metricId, options?)useInputTable(inputTableId, options?)useRows(tableId, options?)useGetFileUrlByFileId(fileId, options?)useGetPublishedWorkbookById(workbookId, options?)useGetTableById(tableId, options?)useGetWorkbooksByType(workbookType, options?)useGetWorkflowInstanceStatusById(instanceId, options?)useGetWorksheets(options?)useGetWorksheetsByType(worksheetType, options?)useRunDefinition(definitionId, options?)useRunPublishedDefinition(publishedDefinitionId, options?)useRunSampleDefinition(sampleDefinitionId, options?)useTriggerHttpWorkflow(workflowId, payload, options?)useTriggerWorkflow(workflowId, options?)useWorkbook(workbookId, options?)useWorkflow(workflowId, options?)useWorksheet(worksheetId, options?)
- Configuration
- Advanced Usage
- Re-exports
- TypeScript Support
- Development
Features
- ✅ First-class TypeScript support with strict type definitions
- 🔁 Seamless integration with TanStack React Query (v5+)
- 🛡 Comprehensive error handling patterns
- ⚙ Optimized default query configuration
- 📦 Re-exports of core TanStack React Query utilities
- 📊 Sample data preview capabilities
- 🧩 Customizable query parameters (limit, caching, retries)
Installation
npm install @bluecopa/react
# or with pnpm
pnpm add @bluecopa/reactPeer Dependencies
This package requires the following in your application:
npm install react@^18.0.0 react-dom@^18.0.0Usage
Query Provider Setup
Wrap your application with the React Query provider:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000, // 1 minute
refetchOnWindowFocus: false,
},
},
});
function App() {
return (
<QueryClientProvider client={queryClient}>
<YourApp />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}Boilerplate Integration
For projects using the Bluecopa React boilerplate, use the pre-configured QueryProvider component that handles API configuration automatically:
// src/providers/query-provider.tsx
import { ReactQueryDevtools, reactQuery, copaSetConfig } from "@bluecopa/react";
import { useEffect, useState } from "react";
const { QueryClient, QueryClientProvider } = reactQuery;
export default function QueryProvider({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(() => new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000, // 1 minute
refetchOnWindowFocus: false,
},
},
}));
useEffect(() => {
let copaUser: any = {};
try {
const copaToken = import.meta.env.VITE_BLUECOPA_API_TOKEN
? atob(import.meta.env.VITE_BLUECOPA_API_TOKEN)
: "{}";
copaUser = JSON.parse(copaToken);
} catch (error) {
console.warn("Failed to parse VITE_BLUECOPA_API_TOKEN:", error);
}
copaSetConfig({
apiBaseUrl: import.meta.env.VITE_BLUECOPA_API_URL || "https://develop.bluecopa.com/api/v1",
workspaceId: import.meta.env.VITE_BLUECOPA_WORKSPACE_ID || "",
accessToken: copaUser?.accessToken || "",
});
}, []);
return (
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}Required Environment Variables:
| Variable | Description | Example |
|----------|-------------|---------|
| VITE_BLUECOPA_API_URL | Base URL for Bluecopa API | https://develop.bluecopa.com |
| VITE_BLUECOPA_WORKSPACE_ID | Your workspace identifier | my-workspace-123 |
| VITE_BLUECOPA_API_TOKEN | Base64-encoded JSON string containing accessToken | eyJhY2Nlc3NUb2tlbiI6IjEyMzQ1In0= |
Example .env file:
VITE_BLUECOPA_API_URL=https://develop.bluecopa.com
VITE_BLUECOPA_WORKSPACE_ID=your-workspace-id
VITE_BLUECOPA_API_TOKEN=base64-encoded-json-hereThen wrap your application with this provider:
import QueryProvider from './providers/query-provider';
function App() {
return (
<QueryProvider>
<YourApp />
</QueryProvider>
);
}This setup automatically configures the API client with your environment-specific settings and applies optimal caching defaults.
Hook Examples
useUser - Fetch authenticated user
import { useUser } from '@bluecopa/react';
function UserProfile() {
const { data, isLoading, error } = useUser({
staleTime: 5 * 60 * 1000, // 5 minutes
retry: 2
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>Welcome, {data?.name}!</div>;
}useDataset - Fetch dataset with query controls
import { useDataset } from '@bluecopa/react';
function DatasetViewer({ datasetId }) {
const { data, isLoading } = useDataset(datasetId, {
limit: 500,
staleTime: 10 * 60 * 1000 // 10 minutes
});
if (isLoading) return <div>Loading dataset...</div>;
return <div>{data?.name} ({data?.records?.length} records)</div>;
}useRows - Fetch input table rows with Supabase-style filtering
import { useRows } from '@bluecopa/react';
function TableRows({ tableId }) {
const { data, isLoading, error } = useRows(tableId, {
status: 'active',
price: 'gte.100',
limit: 25,
offset: 0
});
if (isLoading) return <div>Loading rows...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<div>Total: {data?.total_count ?? 0}</div>
{data?.data?.map(row => <div key={row._copa_id}>{JSON.stringify(row)}</div>)}
</div>
);
}📖 For detailed documentation on useRows including filtering, pagination, and advanced usage, see docs/useRows.md
API Documentation
useUser(options?)
Fetches authenticated user details with query controls.
Parameters:
options(optional): Query options extending TanStack React Query'sUseQueryOptions
Returns:
data: User object orundefinedisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useDataset(datasetId, options?)
Fetches dataset data by ID with configurable parameters.
Parameters:
datasetId: ID of the dataset to fetchoptions(optional): Query options with:limit: Maximum records to fetchstaleTime: Duration (ms) before data is considered stale
Returns:
data: Dataset object containing name and recordsisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useDatasetSample(datasetId, options?)
Fetches a representative sample of dataset data.
Parameters:
datasetId: ID of the datasetoptions(optional): Query options withenabledflag
Returns:
data: Object containing sample dataisLoading: Boolean indicating loading staterefetch: Function to manually trigger refetch
useMetric(metricId, options?)
Fetches metric data by ID.
Parameters:
metricId: ID of the metricoptions(optional): Query options
Returns:
data: Metric object with name and valueisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useInputTable(inputTableId, options?)
Fetches input table data with limit parameters.
Parameters:
inputTableId: ID of the input tableoptions(optional): Query options withlimitParams:limit: Maximum rows to fetchlimitFrom: Direction to apply limit from ('top' or 'bottom')
Returns:
data: Input table object with rowsisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useRows(tableId, options?)
Fetches rows from an input table with Supabase-style filtering, pagination, and sorting. Supports advanced filtering operators and group expressions.
Parameters:
tableId: ID of the input table (string | null | undefined)options(optional): Query options extendingGetRowsOptionsandBaseQueryOptions:limit: Maximum rows to fetch (1-10000)offset: Number of rows to skiporder: Sort order ('asc' or 'desc')order_by: Column name to sort by- Filter fields: Any column name with Supabase-style operator syntax (e.g.,
status: 'active',price: 'gte.100',status: 'in.(active,pending)') or: Supabase/PostgREST group expression for OR conditionsand: Supabase/PostgREST group expression for AND conditions- React Query options:
enabled,staleTime,gcTime,retry,retryDelay,onSuccess,onError
Returns:
data:GetRowsResponseobject containing:data: Array of row objectscount: Number of rows in current pagetotal_count: Total rows available
isLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
Example:
const { data, isLoading } = useRows('table-123', {
status: 'active',
price: 'gte.100',
limit: 25,
offset: 0
});📖 For comprehensive documentation including all supported operators, filtering patterns, and advanced usage, see docs/useRows.md
useGetFileUrlByFileId(fileId, options?)
Fetches the URL for a file by its ID.
Parameters:
fileId: ID of the file to fetch URL foroptions(optional): Query options extending TanStack React Query'sUseQueryOptions
Returns:
data: Object containing file URLisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useGetPublishedWorkbookById(workbookId, options?)
Fetches published workbook details by ID.
Parameters:
workbookId: ID of the published workbookoptions(optional): Query options
Returns:
data: Published workbook objectisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useGetTableById(tableId, options?)
Fetches table metadata by ID.
Parameters:
tableId: ID of the tableoptions(optional): Query options
Returns:
data: Table metadata objectisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useGetWorkbooksByType(workbookType, options?)
Fetches workbooks filtered by type.
Parameters:
workbookType: Type of workbooks to fetchoptions(optional): Query options
Returns:
data: Array of workbook objectsisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useGetWorkflowInstanceStatusById(instanceId, options?)
Fetches workflow instance status by ID.
Parameters:
instanceId: ID of the workflow instanceoptions(optional): Query options
Returns:
data: Workflow status objectisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useGetWorksheets(options?)
Fetches all available worksheets.
Parameters:
options(optional): Query options
Returns:
data: Array of worksheet objectsisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useGetWorksheetsByType(worksheetType, options?)
Fetches worksheets filtered by type.
Parameters:
worksheetType: Type of worksheets to fetchoptions(optional): Query options
Returns:
data: Array of worksheet objectsisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useRunDefinition(definitionId, options?)
Executes a run definition.
Parameters:
definitionId: ID of the run definitionoptions(optional): Query options
Returns:
data: Execution resultisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useRunPublishedDefinition(publishedDefinitionId, options?)
Executes a published run definition.
Parameters:
publishedDefinitionId: ID of the published definitionoptions(optional): Query options
Returns:
data: Execution resultisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useRunSampleDefinition(sampleDefinitionId, options?)
Executes a sample run definition.
Parameters:
sampleDefinitionId: ID of the sample definitionoptions(optional): Query options
Returns:
data: Sample execution resultisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useTriggerHttpWorkflow(workflowId, payload, options?)
Triggers an HTTP workflow execution.
Parameters:
workflowId: ID of the workflowpayload: Request payloadoptions(optional): Query options
Returns:
data: Workflow execution responseisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useTriggerWorkflow(workflowId, options?)
Triggers a workflow execution.
Parameters:
workflowId: ID of the workflowoptions(optional): Query options
Returns:
data: Workflow execution responseisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useWorkbook(workbookId, options?)
Fetches workbook details by ID.
Parameters:
workbookId: ID of the workbookoptions(optional): Query options
Returns:
data: Workbook objectisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useWorkflow(workflowId, options?)
Fetches workflow configuration by ID.
Parameters:
workflowId: ID of the workflowoptions(optional): Query options
Returns:
data: Workflow configuration objectisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
useWorksheet(worksheetId, options?)
Fetches worksheet details by ID.
Parameters:
worksheetId: ID of the worksheetoptions(optional): Query options
Returns:
data: Worksheet objectisLoading: Boolean indicating loading stateerror: Error object if request failedrefetch: Function to manually trigger refetch
Configuration
Default Query Configuration
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 3,
staleTime: 1000 * 60 * 5, // 5 minutes
gcTime: 1000 * 60 * 10, // 10 minutes
},
},
});Customizable Parameters
All hooks accept standard TanStack React Query options:
interface QueryOptions {
enabled?: boolean; // Enable/disable query
staleTime?: number; // Duration (ms) before data is stale
gcTime?: number; // Duration (ms) to keep data in cache
retry?: number | boolean; // Number of retries or disable retries
onSuccess?: (data: any) => void; // Success callback
onError?: (error: Error) => void; // Error callback
}Advanced Usage
Error Handling
useUser({
onError: (error) => {
console.error('User fetch failed:', error.message);
// Custom error recovery logic
}
});Manual Refetching
function ManualRefetch() {
const { data, refetch } = useUser();
return (
<div>
<button onClick={() => refetch()}>Refresh</button>
</div>
);
}Re-exports
This package re-exports core TanStack React Query utilities:
import {
useQuery,
useMutation,
QueryClient,
QueryClientProvider,
ReactQueryDevtools
} from '@bluecopa/react';TypeScript Support
Fully typed with TypeScript. All hooks provide proper type inference and IntelliSense support. Extend types for custom use cases:
import { User } from '@bluecopa/react';
interface CustomUser extends User {
role: string;
permissions: string[];
}Development
# Install dependencies
pnpm install
# Build the package
pnpm build
# Run development server
pnpm dev
# Run tests
pnpm test
# Run tests in watch mode
pnpm test:watch
# Lint code
pnpm lint
# Format code
pnpm format