UNPKG

@splitsoftware/splitio-react

Version:

A React library to easily integrate and use Split JS SDK

42 lines (41 loc) 2.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useTreatment = void 0; var tslib_1 = require("tslib"); var React = (0, tslib_1.__importStar)(require("react")); var memoize_one_1 = (0, tslib_1.__importDefault)(require("memoize-one")); var utils_1 = require("./utils"); var useSplitClient_1 = require("./useSplitClient"); function evaluateFeatureFlag(client, _lastUpdate, names, attributes, _clientAttributes, _flagSets, options, factory) { return client && client.getStatus().isOperational ? client.getTreatment(names[0], attributes, options) : (0, utils_1.getTreatment)(names[0], false, factory); } function memoizeGetTreatment() { return (0, memoize_one_1.default)(evaluateFeatureFlag, utils_1.argsAreEqual); } /** * `useTreatment` is a hook that returns an Split Context object extended with a `treatment` property. * It uses the `useSplitClient` hook to access the client, and invokes the `client.getTreatment()` method. * * @param options - An options object with a feature flag name to evaluate, and an optional `attributes` and `splitKey` values to configure the client. * @returns A Split Context object extended with a Treatment instance, that might be a control treatment if the client is not available or ready, or if the provided feature flag name does not exist. * * @example * ```js * const { treatment, isReady, isReadyFromCache, hasTimedout, lastUpdate, ... } = useTreatment({ name: 'feature_1'}); * ``` * * @see {@link https://developer.harness.io/docs/feature-management-experimentation/sdks-and-infrastructure/client-side-sdks/javascript-sdk/#multiple-evaluations-at-once} */ function useTreatment(options) { var context = (0, useSplitClient_1.useSplitClient)((0, tslib_1.__assign)((0, tslib_1.__assign)({}, options), { attributes: undefined })); var factory = context.factory, client = context.client, lastUpdate = context.lastUpdate; var name = options.name, attributes = options.attributes, properties = options.properties; var getTreatment = React.useMemo(memoizeGetTreatment, []); // Shallow copy `client.getAttributes` result for memoization, as it returns the same reference unless `client.clearAttributes` is invoked. // Note: the same issue occurs with the `names` and `attributes` arguments if they are mutated directly by the user instead of providing a new object. var treatment = getTreatment(client, lastUpdate, [name], attributes, client ? (0, tslib_1.__assign)({}, client.getAttributes()) : {}, undefined, properties && { properties: properties }, factory); return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, context), { treatment: treatment }); } exports.useTreatment = useTreatment;