Utilities
The @blocklet/payment-react library exports several utility functions and classes to simplify common tasks in your application, such as client-side caching, date formatting, and internationalization. These tools are designed to work seamlessly with the library's components and the underlying payment infrastructure.
CachedRequest#
The CachedRequest class offers a straightforward way to implement client-side caching, reducing redundant network calls and improving your application's responsiveness. It supports multiple caching strategies and time-to-live (TTL) configurations.
Usage#
To use it, create an instance of CachedRequest with a unique key, a data-fetching function, and optional configuration.
import { CachedRequest, api } from '@blocklet/payment-react';
// Create a cached request instance
const priceRequest = new CachedRequest(
'product-prices',
() => api.get('/api/prices'),
{
strategy: 'session', // 'session' | 'local' | 'memory'
ttl: 5 * 60 * 1000 // Cache for 5 minutes
}
);
// Use the cached request
async function fetchPrices() {
// This will use the cache if available and not expired
const prices = await priceRequest.fetch();
// To bypass the cache and force a network request
const freshPrices = await priceRequest.fetch(true);
return prices;
}Configuration Options#
Option | Type | Description |
|---|---|---|
|
| The caching strategy to use. |
|
| Time-to-live in milliseconds. After this duration, the cached data is considered expired. Defaults to |
Date Handling with dayjs#
The library exports a pre-configured dayjs instance with useful plugins already enabled, including relativeTime, localizedFormat, utc, and timezone. This ensures consistent date and time handling across your application.
import { dayjs } from '@blocklet/payment-react';
// Format the current date
const formattedDate = dayjs().format('YYYY-MM-DD');
// Parse a timestamp and get its Unix value
const timestamp = 1672531200000;
const dateObject = dayjs(timestamp);
const unixValue = dateObject.unix();
// Display relative time
const fiveMinutesAgo = dayjs().subtract(5, 'minute');
const relativeString = dayjs().from(fiveMinutesAgo); // "5 minutes ago"Internationalization (i18n)#
For applications targeting a global audience, the library includes utilities to manage translations.
createTranslator#
You can create your own translator instance with custom language packs.
import { createTranslator } from '@blocklet/payment-react';
const myTranslations = {
en: {
checkout: { title: 'Complete Payment' }
},
zh: {
checkout: { title: '完成支付' }
}
};
const translator = createTranslator({ fallbackLocale: 'en' }, myTranslations);
console.log(translator('checkout.title', 'zh')); // Outputs: '完成支付'Merging with Library Translations#
To leverage the built-in translations for payment components, you can merge them with your application's translation files.
import { translations as paymentTranslations } from '@blocklet/payment-react';
import merge from 'lodash/merge';
import en from './en'; // Your app's English translations
import zh from './zh'; // Your app's Chinese translations
export const translations = merge(
{
zh,
en,
},
paymentTranslations
);Lazy Loading Components#
To optimize your application's bundle size, you can use the createLazyComponent utility to dynamically load components only when they are needed.
import { createLazyComponent } from '@blocklet/payment-react';
const LazyLoadedComponent = createLazyComponent(async () => {
// Dynamically import the component and its dependencies
const [{ Component }, { useHook }] = await Promise.all([
import('./Component'),
import('./hooks')
]);
// Make dependencies available if needed
globalThis.__DEPENDENCIES__ = { useHook };
return Component;
});
function App() {
return (
<div>
<LazyLoadedComponent />
</div>
);
}These utilities provide robust solutions for common development challenges. To further customize the look and feel of your payment flows, proceed to the Theming guide.