
Security News
Package Maintainers Call for Improvements to GitHub’s New npm Security Plan
Maintainers back GitHub’s npm security overhaul but raise concerns about CI/CD workflows, enterprise support, and token management.
@subscribe.dev/react
Advanced tools
React hooks and components for SubscribeDev - provides context and hooks for managing AI predictions with billing and rate limiting
React hooks and components for SubscribeDev - provides context and hooks for managing AI predictions with billing and rate limiting.
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.
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>
)
}
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>
)
}
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>
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
})
Get account balance information.
const { balance, loading, error, refetch } = useBalance()
// balance.project - project balance
// balance.user - user balance (if userKey provided)
Check user subscription status (requires userKey).
const {
subscription,
loading,
error,
refetch,
isActive,
hasSubscription
} = useSubscription()
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'
})
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()
Get current rate limit information.
const { rateLimits, loading, error, refetch } = useRateLimits()
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])
Get the full context value including client and config.
const { client, config } = useSubscribeDev()
Get just the client instance.
const client = useSubscribeDevClient()
// Use client methods directly
const prediction = await client.run('model', { input: {...} })
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
}
Check subscription status before allowing access to features:
function ProtectedFeature() {
const { isActive, loading } = useSubscription()
if (loading) return <Spinner />
if (!isActive) return <SubscribePrompt />
return <AIFeature />
}
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>
)
}
This package is built with TypeScript and exports all necessary types:
import type {
Prediction,
BalanceInfo,
SubscriptionStatus,
UsePredictionResult
} from '@subscribe.dev/react'
MIT
FAQs
React hooks and components for SubscribeDev - provides context and hooks for managing AI predictions with billing and rate limiting
The npm package @subscribe.dev/react receives a total of 3,731 weekly downloads. As such, @subscribe.dev/react popularity was classified as popular.
We found that @subscribe.dev/react demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
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.
Security News
Maintainers back GitHub’s npm security overhaul but raise concerns about CI/CD workflows, enterprise support, and token management.
Product
Socket Firewall is a free tool that blocks malicious packages at install time, giving developers proactive protection against rising supply chain attacks.
Research
Socket uncovers malicious Rust crates impersonating fast_log to steal Solana and Ethereum wallet keys from source code.