useSDK Hook

The useSDK hook provides access to the SDK context, including initialization state, organization information, and API methods.

Import

import { useSDK, useSDKReady } from '@doccentral/react';

useSDK

Returns the full SDK context value with all properties and methods.

Basic Usagetsx
function MyComponent() {
  const sdk = useSDK();

  if (sdk.isValidating) {
    return <div>Initializing SDK...</div>;
  }

  if (sdk.validationError) {
    return <div>Error: {sdk.validationError}</div>;
  }

  return (
    <div>
      <p>Organization: {sdk.organizationName}</p>
      <p>Scopes: {sdk.scopes.join(', ')}</p>
    </div>
  );
}

Return Value

PropTypeDefaultDescription
isInitializedboolean-Whether the SDK has successfully validated the API key and is ready to use.
isValidatingboolean-Whether the SDK is currently validating the API key. True during initial load.
validationErrorstring | null-Error message if API key validation failed, null otherwise.
organizationIdstring | null-The organization ID associated with the validated API key.
organizationNamestring | null-The organization name associated with the validated API key.
scopesstring[]-Array of permission scopes granted to the API key.
configSDKConfig-The current SDK configuration object.
apiRequest<T>(endpoint: string, options?: RequestInit) => Promise<T>-Method to make authenticated API requests to the DocCentral backend.

Provider Required

useSDK must be used within a DocCentralProvider. Using it outside will throw an error:"useSDK must be used within a DocCentralProvider"

useSDKReady

A convenience hook that returns a simple boolean indicating if the SDK is ready to use.

useSDKReadytsx
function MyComponent() {
  const isReady = useSDKReady();

  if (!isReady) {
    return <LoadingSpinner />;
  }

  return <DocumentViewer />;
}

// Equivalent to:
function useSDKReady(): boolean {
  const { isInitialized, isValidating } = useSDK();
  return isInitialized && !isValidating;
}

Making API Requests

The apiRequest method allows you to make authenticated requests to the DocCentral API. It automatically includes the API key and handles timeouts.

API Requeststsx
function DocumentLoader({ documentId }: { documentId: string }) {
  const { apiRequest, isInitialized } = useSDK();
  const [document, setDocument] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!isInitialized) return;

    async function loadDocument() {
      try {
        const data = await apiRequest<DocumentResponse>(
          `/sdk/documents/${documentId}`
        );
        setDocument(data);
      } catch (error) {
        console.error('Failed to load document:', error);
      } finally {
        setLoading(false);
      }
    }

    loadDocument();
  }, [documentId, apiRequest, isInitialized]);

  if (loading) return <div>Loading...</div>;
  return <div>{document?.filename}</div>;
}

POST Request Example

POST Requesttsx
async function submitDocument(payload: DocumentSubmissionPayload) {
  const { apiRequest } = useSDK();

  const result = await apiRequest<SubmissionResponse>('/sdk/documents/submit', {
    method: 'POST',
    body: JSON.stringify(payload),
  });

  return result;
}

Checking Scopes

Use the scopes array to check if the current API key has specific permissions:

Scope Checkingtsx
function SubmitButton() {
  const { scopes } = useSDK();
  
  const canSubmit = scopes.includes('documents:submit');
  const canRead = scopes.includes('documents:read');

  if (!canSubmit) {
    return (
      <Tooltip content="Your API key doesn't have submit permissions">
        <button disabled>Submit Document</button>
      </Tooltip>
    );
  }

  return <button onClick={handleSubmit}>Submit Document</button>;
}

Configuration Access

Access the current SDK configuration through the config property:

Config Accesstsx
function DebugPanel() {
  const { config } = useSDK();

  if (!config.debug) return null;

  return (
    <div className="debug-panel">
      <p>API Base URL: {config.apiBaseUrl}</p>
      <p>Timeout: {config.timeout}ms</p>
      <p>Custom Headers: {Object.keys(config.customHeaders || {}).length}</p>
    </div>
  );
}

TypeScript Interface

types.tstypescript
interface SDKContextValue {
  /** Whether the SDK is initialized */
  isInitialized: boolean;
  /** Whether the SDK is validating the API key */
  isValidating: boolean;
  /** Validation error if any */
  validationError: string | null;
  /** Organization ID from validated API key */
  organizationId: string | null;
  /** Organization name */
  organizationName: string | null;
  /** API scopes */
  scopes: string[];
  /** SDK configuration */
  config: SDKConfig;
  /** Make an authenticated request to the API */
  apiRequest: <T>(endpoint: string, options?: RequestInit) => Promise<T>;
}

interface SDKConfig {
  apiBaseUrl: string;
  apiKey: string;
  debug?: boolean;
  customHeaders?: Record<string, string>;
  timeout?: number;
}

Error Handling

Error Handlingtsx
function SDKErrorBoundary({ children }: { children: React.ReactNode }) {
  const { validationError, isValidating } = useSDK();

  if (isValidating) {
    return <FullPageLoader message="Initializing SDK..." />;
  }

  if (validationError) {
    return (
      <ErrorDisplay
        title="SDK Initialization Failed"
        message={validationError}
        actions={[
          { label: 'Retry', onClick: () => window.location.reload() },
          { label: 'Contact Support', href: '/support' },
        ]}
      />
    );
  }

  return <>{children}</>;
}