@andre1502/react-utilities
v1.2.0
Published
module to combine common functions
Readme
react-utilities
Library to combine common functions
Installation
yarn add @andre1502/react-utilitiesOR
npm install @andre1502/react-utilitiesUsage
Config & Locales CLI
- Get Google service account credentials from https://console.cloud.google.com/apis/credentials.
- Add
GOOGLE_APPLICATION_CREDENTIALSas system environment variable with value of Google service account file credentials location.
Credentials
The fetch functions (fetchLocales, fetchConfig, fetchAll, fetchRawValue) read the Google Sheet with the first of these that is set:
| Order | Credential | Use it when |
|---|---|---|
| 1 | GOOGLE_SHEETS_ACCESS_TOKEN environment variable: an access token with the scope https://www.googleapis.com/auth/spreadsheets.readonly | the service account key must not be where the fetch runs (a sandbox, a shared CI runner) |
| 2 | google_application_credentials.json in the folder the command runs in: the service account key | local development (the usual way) |
| 3 | GOOGLE_APPLICATION_CREDENTIALS environment variable: the path of the key | the key is kept somewhere else |
Never commit the key file or a token, and never print them in logs. The key file is in .gitignore.
Get an access token for GOOGLE_SHEETS_ACCESS_TOKEN
An access token is made from the service account key, on a machine that has the key. It is valid for 1 hour and only for reading Google Sheets. The library uses it as it is: it does not renew it, so make a new one for each run (or let whatever provides it renew it).
With google-auth-library (already a dependency of this package), in a file such as print-sheets-token.mjs:
import { GoogleAuth } from 'google-auth-library';
const auth = new GoogleAuth({
keyFile: 'google_application_credentials.json',
scopes: ['https://www.googleapis.com/auth/spreadsheets.readonly'],
});
console.log(await auth.getAccessToken());Then pass the token to the fetch in the same command, so it is never saved in a file or in your shell history:
GOOGLE_SHEETS_ACCESS_TOKEN="$(node print-sheets-token.mjs)" node fetchConfig.jsWhen a proxy adds the real token to requests (for example a sandbox whose proxy replaces a stand-in value in the Authorization header sent to sheets.googleapis.com), set GOOGLE_SHEETS_ACCESS_TOKEN to the stand-in value: the library sends it as Authorization: Bearer <value> and the proxy swaps it.
Fetch Locales
Filename will be auto defined by locales key (e.g. zh-TW, filename will be zh-tw.json).
import { fetchLocales } from '@andre1502/react-utilities/cli';
// OR
import { fetchLocales } from '@andre1502/react-utilities/config-cli';
// https://docs.google.com/spreadsheets/d/<google-sheet-id>/edit
const optionLocales = {
spreadsheetId: '', // Google Sheet Id
spreadsheetTab: '', // Google Sheet Tab for locales
formatAs: 'locales',
output: {
folder: './src/locales', // locales folder location
isFilenameLowercase: true, // set if filename need to be lowercase
exportAs: 'ts', // export locales as 'ts' | 'json'
},
};
fetchLocales(optionLocales);Fetch Config
Config file only support export as js file, since you need to combine it with transform function.
import { fetchConfig } from '@andre1502/react-utilities/cli';
// OR
import { fetchConfig } from '@andre1502/react-utilities/config-cli';
// https://docs.google.com/spreadsheets/d/<google-sheet-id>/edit
const optionConfig = {
spreadsheetId: '', // Google Sheet Id
spreadsheetTab: '', // Google Sheet Tab for config;
formatAs: 'config',
output: {
folder: '.', // config folder location
filename: 'versionConfig', // config filename
isFilenameLowercase: false, // set if filename need to be lowercase
exportAs: 'json', // export config as 'ts' | 'json' | 'js'
},
};
fetchConfig(optionConfig);Config output example
module.exports = {
params: {
'<app-brand>': {
API_MAIN_URL: {
dev: '<api-dev>',
stag: '<api-staging>',
prod: '<api-production>',
},
},
},
};{
"params": {
"<app-brand>": {
"API_MAIN_URL": {
"dev": "<api-dev>",
"stag": "<api-staging>",
"prod": "<api-production>"
}
}
}
}Fetch All
To fetch both locales and config.
import { fetchAll } from '@andre1502/react-utilities/cli';
// OR
import { fetchAll } from '@andre1502/react-utilities/config-cli';
// https://docs.google.com/spreadsheets/d/<google-sheet-id>/edit
const spreadsheetId = ''; // Google Sheet Id
const spreadsheetLocalesTab = ''; // Google Sheet Tab for locales
const spreadsheetConfigTab = ''; // Google Sheet Tab for config;
const optionLocales = {
spreadsheetId: spreadsheetId,
spreadsheetTab: spreadsheetLocalesTab,
formatAs: 'locales',
output: {
folder: './src/locales', // locales folder location
isFilenameLowercase: true, // set if filename need to be lowercase
exportAs: 'ts', // export locales as 'ts' | 'json'
},
};
const optionConfig = {
spreadsheetId: spreadsheetId,
spreadsheetTab: spreadsheetConfigTab,
formatAs: 'config',
output: {
folder: '.', // config folder location
filename: 'versionConfig', // config filename
isFilenameLowercase: false, // set if filename need to be lowercase
exportAs: 'json', // export locales as 'ts' | 'json' | 'js'
},
};
fetchAll([optionLocales, optionConfig]);Transform Config
import { transformConfig } from '@andre1502/react-utilities/cli';
// OR
import { transformConfig } from '@andre1502/react-utilities/config-cli';
const version = '<app-brand>';
const env = '<env-value>'; // support 'dev' | 'stag' | 'prod'
import versionConfig from './versionConfig.json' with { type: 'json' };
const currentConfig = {
...versionConfig.params.default,
...versionConfig.params[version],
};
transformConfig(currentConfig, env, 'REACT_APP_', {
folder: '.', // transformed config folder location
filename: '.env', // transformed config filename
isFilenameLowercase: false, // set if filename need to be lowercase
exportAs: 'env', // export transformed config as 'ts' | 'js' | 'env'
});Transform Sitemap
import { transformSitemap } from '@andre1502/react-utilities/cli';
// OR
import { transformSitemap } from '@andre1502/react-utilities/config-cli';
const version = '<app-brand>';
const env = '<env-value>'; // support 'dev' | 'stag' | 'prod'
import versionConfig from './versionConfig.json' with { type: 'json' };
const currentConfig = {
...versionConfig.params.default,
...versionConfig.params[version],
};
const hostname = currentConfig['MAIN_URL'][env];
const urls = currentConfig['SITEMAP'];
transformSitemap(hostname, urls, true, {
folder: './public', // transformed sitemap folder location
filename: 'sitemap.xml', // transformed sitemap filename
isFilenameLowercase: false, // set if filename need to be lowercase
});Sentry
Peer Dependencies
To use Sentry utilities, ensure you have the appropriate Sentry SDK installed in your project:
- Web (React):
npm install @sentry/reactoryarn add @sentry/react - Mobile (React Native):
npm install @sentry/react-nativeoryarn add @sentry/react-native
Both are optional peer dependencies: this package installs neither (since 1.2.0, @sentry/react-native is no longer installed with it), so a web project does not get the React Native SDK and its build tools. Only @andre1502/react-utilities/sentry needs @sentry/react, and only @andre1502/react-utilities/sentry-rn and /react-native need @sentry/react-native.
Personal data (sendDefaultPii, dataCollection)
Sentry 11 replaced its sendDefaultPii option with dataCollection, which turns each kind of collected data on or off. initSentry (React) keeps sendDefaultPii as its own option and turns it into dataCollection:
| sendDefaultPii | dataCollection given to Sentry |
|---|---|
| false (default) | { userInfo: false, cookies: false, httpHeaders: false, httpBodies: [], urlQueryParams: false }: no personal data |
| true | { userInfo: true, cookies: true, httpHeaders: true, urlQueryParams: true } (Sentry still filters values such as tokens and keys) |
To choose each category yourself, pass dataCollection (Sentry's own shape); it is used as it is. With Sentry 10 or older, sendDefaultPii is passed to Sentry too, as before.
Init Sentry for React
import { initSentry } from '@andre1502/react-utilities';
// OR
import { initSentry } from '@andre1502/react-utilities/sentry';
initSentry({
env: '',
dsn: '',
debug: false,
release: '',
requiredEnvForSendToSentry: ['production'],
sendDefaultPii: false, // Optional: defaults to false for privacy/GDPR compliance
// dataCollection: { userInfo: false, cookies: { deny: ['session'] } }, // Optional: Sentry 11's own setting, used as it is
httpClientIntegrationOptions: {
failedRequestStatusCodes: [[400], [402, 499], [500, 599]],
failedRequestTargets: ['http://localhost'],
},
captureConsoleIntegrationOptions: {
levels: ['error'],
},
options: {
// other sentry options
// ...
integrations: [
// other sentry integrations
// ...
],
},
});Init Sentry for React Native
import { initSentry } from '@andre1502/react-utilities/react-native';
// OR
import { initSentry } from '@andre1502/react-utilities/sentry-rn';
initSentry({
env: '',
dsn: '',
debug: false,
requiredEnvForSendToSentry: ['production'],
sendDefaultPii: false, // Optional: defaults to false for privacy
attachScreenshot: false, // Optional: defaults to false for privacy
httpClientIntegrationOptions: {
failedRequestStatusCodes: [[400], [402, 499], [500, 599]],
failedRequestTargets: ['http://localhost'],
},
captureConsoleIntegrationOptions: {
levels: ['error'],
},
options: {
// other sentry options
// ...
integrations: [
// other sentry integrations
// ...
],
},
});Format Number
formatAccountNumber
import { formatAccountNumber } from '@andre1502/react-utilities';
// OR
import { formatAccountNumber } from '@andre1502/react-utilities/format';
const accountNumber = '1234567890123456';
const separator = ' ';
const result = formatAccountNumber(data, separator);
console.log(`result: ${result}`);
// output: 1234 5678 9012 3456formatNumber
import { formatNumber } from '@andre1502/react-utilities';
// OR
import { formatNumber } from '@andre1502/react-utilities/format';
const result = formatNumber({
lang: 'zh-TW',
currency: 'TWD',
value: 1000,
showValue: true,
showCurrency: true,
});
console.log(`result: ${result}`);
// output showValue(true) showCurrency(true): 'NT$ 1,000'
// output showValue(true) showCurrency(false): '1,000'
// output showValue(false) showCurrency(true): 'NT$ ********'
// output showValue(false) showCurrency(false): '********'getCurrencySymbol
import { getCurrencySymbol } from '@andre1502/react-utilities';
// OR
import { getCurrencySymbol } from '@andre1502/react-utilities/format';
const currency = 'TWD';
const showCurrency = true;
const result = getCurrencySymbol(currency, showCurrency);
console.log(`result: ${result}`);
// output showCurrency(true): 'NT$'
// output showCurrency(false): ''parseFormatNumber
import { parseFormatNumber } from '@andre1502/react-utilities';
// OR
import { parseFormatNumber } from '@andre1502/react-utilities/format';
const lang = 'zh-TW';
const value = '1,000';
const result = parseFormatNumber(lang, value);
console.log(`result: ${result}`);
// output: 1000I18n
import { initReactI18next } from 'react-i18next';
import { version } from './package.json';
import enUS from './en-US.json';
// ---
import { EnvironmentEnum, initI18n } from '@andre1502/react-utilities';
// OR
import { EnvironmentEnum, initI18n } from '@andre1502/react-utilities/i18n';
const localLang = 'en-US';
const fallbackLang = 'en-US';
const langCacheExpiredTimeMs = 24 * 60 * 60 * 1000;
// translation language from json file.
const resources = {
'en-US': { translation: enUS },
};
// determine whether need to use backend support to load resources.
const useBackend = false;
// optional, if false or undefined will use resources value
const withLocalstorageBackend = false;
// change this to real CDN url or cloud storage with direct access like AWS S3 or GCP cloud storage.
// optional, if empty, false or undefined will use resources value
const cdnUrl = 'http://cdnurl.com';
// optional, if false or undefined disable debug mode
const debug = false;
initI18n({
initReactI18next: initReactI18next,
lang: localLang,
fallbackLang: fallbackLang,
langCacheExpiredTimeMs: langCacheExpiredTimeMs,
resources: resources,
version: version,
useBackend: useBackend,
withLocalstorageBackend: withLocalstorageBackend,
cdnUrl: cdnUrl,
debug: debug,
});Utils
parseQueryString
Parses a full URL or query string into a structured object with originValue, safely sanitized against prototype pollution (__proto__, constructor, prototype).
import { parseQueryString } from '@andre1502/react-utilities';
// OR
import { parseQueryString } from '@andre1502/react-utilities/utils';
const parsed = parseQueryString('https://example.com/api?user=john&token=abc=123');
console.log(parsed.originValue); // 'https://example.com/api'
console.log(parsed.user); // 'john'
console.log(parsed.token); // 'abc=123'getUniquePermutations
Calculates all unique permutations of a specified length. Includes an optional maxLength parameter to guard against algorithmic DoS / factorial memory spikes.
import { getUniquePermutations } from '@andre1502/react-utilities';
// OR
import { getUniquePermutations } from '@andre1502/react-utilities/utils';
// Standard permutations
const perms = getUniquePermutations(['A', 'B', 'C'], 2);
// Output: [['A', 'B'], ['A', 'C'], ['B', 'A'], ['B', 'C'], ['C', 'A'], ['C', 'B']]
// With optional maxLength safeguard (throws Error if input length > maxLength)
const safePerms = getUniquePermutations(['A', 'B', 'C'], 2, 5);Pagination Helpers
import { getItemRow, getNextPage, getTotalPages } from '@andre1502/react-utilities/utils';
// Calculate 1-based table row index: index 0 on page 2 with pageSize 10 -> row 11
const row = getItemRow(0, 2, 10);
// Calculate total pages: 25 records with pageSize 10 -> 3 pages
const totalPages = getTotalPages(10, 25);
// Calculate next page: on page 1 of 3 -> 2 (returns undefined if on last page)
const nextPage = getNextPage(1, 10, 25);Testing
This repository includes a two-layer test suite for both fast development and real-world consumer verification:
# Run all tests (unit tests + standalone consumer pack-and-test)
yarn test
# Run fast in-source unit tests with Vitest
yarn test:unit
# Run automated standalone pack-and-test integration runner
yarn test:standalone- Unit Tests (
yarn test:unit): In-source unit testing with Vitest coveringFormat,Utils,Pagination,I18n, andSentry. - Standalone Pack-and-Test (
yarn test:standalone): Offline verification that buildsdist/, creates a local tarball vianpm pack, installs it in an isolated temporary consumer project, verifies consumer TypeScript typings (tsc --noEmit), and executes runtime assertions without publishing to npm or pushing to git.
Local Testing
If you want to test this library in another local project, here are the most effective ways to do it.
Method 1: The Quickest Way (yarn add)
Best for a 10-second check.
- In your other project:
yarn add ../react-utilities(use the relative path). - Warning: This uses symlinks. If you get a "Duplicate React" or "Invalid Hook Call" error, use Method 2.
Method 2: The Recommended Way (yalc)
Best for active development. It avoids all symlink/React issues by copying files instead of linking them.
In this library:
- Install yalc globally:
npm i -g yalc - Build and publish locally:
yarn build && yalc publish - (Optional) For auto-syncing:
yarn build:watchand in another terminalyalc publish --push
In your other project:
- Add the local package:
yalc add @andre1502/react-utilities - Install dependencies:
yarn install(or npm/pnpm)
Method 3: The "Clean" Way (npm pack)
Best for final verification before publishing.
In this library:
yarn buildnpm pack(this creates a.tgzfile likeandre1502-react-utilities-1.0.9.tgz)
In your other project:
yarn add ./path/to/andre1502-react-utilities-1.0.9.tgz
💖 Support the Project
If this project saved you time or helped you build something cool, consider a one-time donation!
| Amount | Goal | | :-- | :-- | | $5 USD | ☕ Buy me a coffee | | $15 USD | 🍕 Buy me a pizza | | $50 USD | 🛠️ Support a new feature | | Custom | 🚀 Every bit helps! |
Note: 100% of your donation goes to development (excluding PayPal's standard transaction fee).
