Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

@subscribe.dev/react

Package Overview
Dependencies
Maintainers
1
Versions
95
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@subscribe.dev/react

React hooks and components for SubscribeDev - provides context and hooks for managing AI predictions with billing and rate limiting

Source
npmnpm
Version
0.0.9
Version published
Weekly downloads
6.4K
-35.11%
Maintainers
1
Weekly downloads
 
Created
Source

@subscribe.dev/react

React hooks and components for SubscribeDev - provides context and hooks for managing AI predictions with billing and rate limiting.

Installation

npm install @subscribe.dev/react @subscribe.dev/client
# or
yarn add @subscribe.dev/react @subscribe.dev/client
# or
bun add @subscribe.dev/react @subscribe.dev/client

Note: @subscribe.dev/client is a peer dependency and must be installed separately.

Quick Start

1. Wrap your app with the provider

import { SubscribeDevProvider } from '@subscribe.dev/react'

function App() {
  return (
    <SubscribeDevProvider
      config={{
        apiKey: 'pub_your_api_key_here',
        userKey: 'user_your_user_key_here' // Optional, for user-specific features
      }}
    >
      <YourApp />
    </SubscribeDevProvider>
  )
}

2. Use hooks in your components

import { usePrediction, useBalance, useSubscription } from '@subscribe.dev/react'

function AIComponent() {
  const { balance } = useBalance()
  const { subscription, isActive } = useSubscription()
  const { prediction, loading, error, run } = usePrediction()

  const handleRunPrediction = async () => {
    const result = await run('meta/llama-2-70b-chat', {
      input: { 
        prompt: 'Hello, how are you?',
        max_length: 100
      }
    })
    console.log('Prediction result:', result)
  }

  if (!isActive) {
    return <div>Please subscribe to use AI features</div>
  }

  return (
    <div>
      <p>Balance: ${balance?.project?.toFixed(2)}</p>
      <button onClick={handleRunPrediction} disabled={loading}>
        {loading ? 'Running...' : 'Run Prediction'}
      </button>
      {error && <p>Error: {error.message}</p>}
      {prediction && <p>Result: {prediction.output}</p>}
    </div>
  )
}

API Reference

SubscribeDevProvider

The provider component that makes the SubscribeDev client available to child components.

<SubscribeDevProvider
  config={{
    apiKey: 'pub_your_api_key_here',
    userKey: 'user_your_user_key_here', // Optional
    timeout: 300000, // Optional, default 5 minutes
    maxRetries: 2, // Optional
    debug: false // Optional
  }}
  client={existingClient} // Optional, provide your own client instance
>
  {children}
</SubscribeDevProvider>

Hooks

usePrediction

Run AI predictions with automatic state management.

const { prediction, loading, error, run, reset } = usePrediction({
  model: 'meta/llama-2-70b-chat',
  input: { prompt: 'Hello!' },
  response_format: { type: 'json_object' }, // Optional
  autoRun: false // Optional, default false
})

useBalance

Get account balance information.

const { balance, loading, error, refetch } = useBalance()
// balance.project - project balance
// balance.user - user balance (if userKey provided)

useSubscription

Check user subscription status (requires userKey).

const { 
  subscription, 
  loading, 
  error, 
  refetch, 
  isActive, 
  hasSubscription 
} = useSubscription()

useTransactions

Get transaction history with filtering options.

const { transactions, loading, error, refetch } = useTransactions({
  limit: 10,
  offset: 0,
  status: 'succeeded',
  model: 'meta/llama-2-70b-chat',
  startDate: '2023-01-01',
  endDate: '2023-12-31'
})

useStorage

Manage user storage data (requires userKey).

const { 
  storage, 
  loading, 
  error, 
  setStorage, 
  deleteStorage, 
  refetch 
} = useStorage({
  appVersion: '1.0.0' // Optional
})

// Update storage
await setStorage({ key: 'value' })

// Delete storage
await deleteStorage()

useRateLimits

Get current rate limit information.

const { rateLimits, loading, error, refetch } = useRateLimits()

useErrorHandler

Utility hook for handling different error types.

const handleError = useErrorHandler({
  onInsufficientBalance: (error) => {
    console.log('Not enough credits:', error.requiredCredits)
  },
  onRateLimit: (error) => {
    console.log('Rate limited, retry after:', error.retryAfter)
  },
  onUnsubscribed: (error) => {
    console.log('User needs to subscribe')
  },
  onGenericError: (error) => {
    console.log('Generic error:', error.message)
  }
})

// Use with any hook that returns an error
const { error } = usePrediction(...)
useEffect(() => {
  handleError(error)
}, [error, handleError])

Context Hooks

useSubscribeDev

Get the full context value including client and config.

const { client, config } = useSubscribeDev()

useSubscribeDevClient

Get just the client instance.

const client = useSubscribeDevClient()
// Use client methods directly
const prediction = await client.run('model', { input: {...} })

Best Practices

Error Handling

Always handle errors in your components:

function MyComponent() {
  const { prediction, loading, error, run } = usePrediction({...})
  
  if (error) {
    if (error instanceof UnsubscribedError) {
      return <SubscribePrompt />
    }
    if (error instanceof InsufficientBalanceError) {
      return <TopUpPrompt requiredCredits={error.requiredCredits} />
    }
    return <ErrorMessage error={error} />
  }
  
  // ... rest of component
}

Subscription Checks

Check subscription status before allowing access to features:

function ProtectedFeature() {
  const { isActive, loading } = useSubscription()
  
  if (loading) return <Spinner />
  if (!isActive) return <SubscribePrompt />
  
  return <AIFeature />
}

Balance Monitoring

Monitor balance to prevent failed requests:

function SmartAIComponent() {
  const { balance } = useBalance()
  const estimatedCost = 0.01 // Your cost estimation
  
  const canAfford = balance?.project && balance.project >= estimatedCost
  
  return (
    <button disabled={!canAfford}>
      {canAfford ? 'Run AI' : 'Insufficient Balance'}
    </button>
  )
}

TypeScript Support

This package is built with TypeScript and exports all necessary types:

import type { 
  Prediction, 
  BalanceInfo, 
  SubscriptionStatus,
  UsePredictionResult 
} from '@subscribe.dev/react'

License

MIT

Keywords

react

FAQs

Package last updated on 03 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts