@paritydeals/react-sdk provides a seamless way to integrate ParityDeals entitlement management into your React applications.
Overview
- A React Context Provider (
ParityDealsProvider) to initialize and configure the SDK. - Hooks to easily access entitlement status and data within your components.
- Conditional rendering components to show or hide UI elements based on feature access.
- Automatic and manual data fetching and caching mechanisms.
2. Installation
Install the SDK using npm or yarn:react as a peer dependency.
3. Setup & Configuration
ParityDealsProvider
The core of the SDK is the ParityDealsProvider. You need to wrap your application (or the relevant part of it) with this provider. It initializes the SDK and makes entitlement data available to its children components via context.
Required Props for ParityDealsProvider
customerId: string- The ID of the customer for whom entitlements are being fetched. This will be sent as a query parameter (
customer_id).
- The ID of the customer for whom entitlements are being fetched. This will be sent as a query parameter (
accessToken: string | null- Your static API token or Bearer token for authenticating requests to the ParityDeals API. If provided, it will be included in the
Authorization: Bearer <accessToken>header.
- Your static API token or Bearer token for authenticating requests to the ParityDeals API. If provided, it will be included in the
Optional Props for ParityDealsProvider
4. Fetching Entitlements
Automatic Fetching on Mount
By default (fetchEntitlementsOnMount: true in the config prop, or if config or this specific option is omitted), the SDK will attempt to fetch all entitlements for the specified customerId as soon as the ParityDealsProvider is mounted.
The isLoading state from useParityDeals() will be true during this initial fetch.
Manual Fetching
IffetchEntitlementsOnMount is set to false, or if you need to re-fetch entitlements at any point (e.g., after a user action that might change their entitlements), you can use the refreshAllEntitlements function.
5. Accessing Entitlement Data (Hooks)
The SDK provides several hooks to access entitlement data and SDK state.useParityDeals()
This is the primary hook to access the SDK’s context.
- Returns:
ParityDealsContextValueobject containing:allEntitlements: AsyncState<EntitlementMap | null>: The state object for all fetched entitlements.data: AnEntitlementMap(aRecord<string, AnyEntitlement>) where keys arefeatureKeys, ornullif not loaded or error.isLoading: Boolean indicating if theallEntitlementsdata is currently being fetched/refreshed.error: AnErrorobject if the last fetch failed, otherwisenull.
refreshAllEntitlements: () => Promise<void>: Function to manually trigger a re-fetch of all entitlements.getEntitlement: <T extends AnyEntitlement>(featureKey: string, type: T['type']) => AsyncState<T | null>: Function to get a specific entitlement’s state from the cache.hasAccess: (featureKey: string) => boolean | undefined: A utility function to quickly check access for a feature. Returnstrueif access is granted,falseif denied or feature not found, andundefinedif data is loading or an error occurred.isLoading: boolean: A global loading state indicating if the SDK is performing its initial configured fetch or a refresh operation.error: Error | null: A global error state reflecting any error from the last fetch operation initiated by the provider.customerId: string: The customer ID passed to the provider.apiUrl: string: The base API URL passed to the provider.entitlementsPath: string: The entitlements path passed to the provider.
useAllEntitlements()
A convenience hook that directly returns the allEntitlements state object.
- Returns:
AsyncState<EntitlementMap | null>
useBooleanEntitlement(featureKey: string)
Fetches the state for a specific boolean entitlement from the cache.
- Arguments:
featureKey: string: The key of the boolean feature.
- Returns:
AsyncState<BooleanEntitlement | null>
useConfigEntitlement(featureKey: string)
Fetches the state for a specific configuration entitlement from the cache.
- Arguments:
featureKey: string: The key of the configuration feature.
- Returns:
AsyncState<ConfigEntitlement | null>(whereConfigEntitlementhas aconfiguration: number | nullproperty).
useMeteredEntitlement(featureKey: string)
Fetches the state for a specific metered entitlement from the cache.
- Arguments:
featureKey: string: The key of the metered feature.
- Returns:
AsyncState<MeteredEntitlement | null>
6. Conditional Rendering Components
These components provide a declarative way to render UI based on entitlement status. They internally use the respective hooks. Common Props:featureKey: string: The unique key of the feature to check.children: ReactNode | ((data: E) => ReactNode):- If a
ReactNode, it’s rendered when the user is entitled and conditions are met. - If a function (render prop), it’s called with the entitlement data (
BooleanEntitlement,ConfigEntitlement, orMeteredEntitlement) and its return value is rendered.
- If a
fallback?: ReactNode: Content to render if the user is not entitled, or if data is loading (and noloadingComponentis provided), or if an error occurs. Defaults tonull.loadingComponent?: ReactNode: Specific content to render while the entitlement data is loading. Overridesfallbackduring loading.
ShowWhenBooleanEntitled
Renders children if the boolean feature is enabled (hasAccess: true).
ShowWhenConfigEntitled
Renders children if the config feature is enabled and provides the numeric configuration value to the children render prop.
- Children Prop:
(config: number) => ReactNode(Required to be a function for this component).
ShowWhenMeteredEntitled
Renders children if the metered feature is enabled and, by default, if remaining usage is greater than 0 or unlimited (limit is null).
- Optional Prop:
condition?: (data: MeteredEntitlement) => boolean: A custom function to further determine if children should render based on the metered entitlement data.
- Children Prop: Can be
ReactNodeor(data: MeteredEntitlement) => ReactNode.
7. Key Types
The SDK exports several types for better integration with TypeScript. Some key ones include:ParityDealsProviderOptions: Configuration for the provider.ParityDealsContextValue: The shape of the object returned byuseParityDeals().AsyncState<T>: Generic type for asynchronous data states.EntitlementMap: The structure of the cached entitlements (Record<string, AnyEntitlement>).Entitlement,BooleanEntitlement,ConfigEntitlement,MeteredEntitlement: Processed entitlement types.ApiRequestConfig,ApiResponse: Interfaces related to the underlyingapiRequestservice.RawEntitlementsApiResponseand relatedRaw...types: Represent the structure of the direct API response.
@paritydeals/react-sdk/types (assuming your src/types/index.ts re-exports them) or directly from the main SDK entry if configured.
8. Error Handling
- Provider Level: The
onErrorcallback inParityDealsProviderOptionscan be used to globally handle errors that occur during the entitlement fetching process initiated by the provider. - Hook Level: Each hook (
useAllEntitlements,useBooleanEntitlement, etc.) returns anAsyncStateobject which includes anerror: Error | nullproperty. You can check this to handle errors specific to that data slice. - Context Level:
useParityDeals()also returns a globalerror: Error | nullstate, reflecting errors from the provider’s most recent fetch operation.
9. Example Usage
A comprehensive example is provided within the comments of the SDK code, demonstrating provider setup and component usage. The core setup involves:- Wrapping your application with
ParityDealsProviderand providing the required props (customerId,accessToken) - Using hooks like
useBooleanEntitlementor conditional components likeShowWhenBooleanEntitledin your components to control UI and behavior based on entitlements.
10. API Request Service
The SDK relies on anapiRequest function for making HTTP requests. The SDK’s ParityDealsProvider passes configuration like timeout, maxRetries, backoffBaseDelay, and accessToken to this function.
- Your Responsibility: You need to ensure that your project includes an implementation of this
apiRequestservice (e.g., insrc/services/makeRequest.service.ts) that matches theApiRequestConfigandApiResponseinterfaces used by the SDK. This service should handle actual HTTP communication, including appending query parameters passed viaApiRequestConfig.queryParamsand using theaccessTokento set theAuthorizationheader. - The placeholder
apiRequestfunction included in the SDK’s source code is for demonstration and type-checking purposes only and will not make real API calls.
11. Project Structure (for contributors/reference)
The SDK source code (src/) is organized as follows:
components/: Contains conditional rendering React components.ShowWhenBooleanEntitled.tsxShowWhenConfigEntitled.tsxShowWhenMeteredEntitled.tsxShowWhenEntitledInternal.tsx(Internal helper, not typically exported)index.ts(Exports public components)
context/: Defines the React Context.ParityDealsContext.ts
hooks/: Contains all custom React Hooks.useParityDeals.tsuseAllEntitlements.tsuseBooleanEntitlement.tsuseConfigEntitlement.tsuseMeteredEntitlement.tsindex.ts(Exports all hooks)
provider/: Contains the mainParityDealsProvider.ParityDealsProvider.tsx
types/: Contains all TypeScript definitions.api.types.ts(Raw types from API)sdk.types.ts(Processed types for SDK and public use)index.ts(Re-exports all types)
utils/: Contains utility functions.transformations.ts(FortransformApiEntitlements)index.ts(Exports utilities)
index.ts: The main entry point of the SDK, re-exporting all public APIs (provider, hooks, components, types).
Using the Sandbox
If you want to use the sandbox, you need to set theenvironment option to sandbox in the ParityDealsProvider.