Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/browser-opt-in-value.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@reflag/browser-sdk": major
---

Opt-in entries from `getOptInFlags()` now include the flag's `value` instead of `isEnabled`. The deprecated `getFeatures()` alias is removed; use `getFlags()`.
7 changes: 7 additions & 0 deletions .changeset/opt-in-set-from-hook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@reflag/react-sdk": major
"@reflag/vue-sdk": major
"@reflag/react-native-sdk": major
---

`useOptInFlags()` now returns `setOptIn` along with `flags` and `isLoading`. `useSetOptIn()` still works but is deprecated. Opt-in entries now include the flag's `value` instead of `isEnabled`. The deprecated `useFeature()` alias is removed from React and React Native; use `useFlag()`.
5 changes: 3 additions & 2 deletions packages/browser-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ try {
}
```

Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `reflag.refresh()` to retry.
Each entry includes the flag's `key`, `name`, `description` and `value`, and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `reflag.refresh()` to retry.

## Tracking, feedback and events

Expand All @@ -136,7 +136,8 @@ Use `track(eventName, attributes?)`, `feedback(payload)` and `requestFeedback({
- Move remote config to a multivariate flag and read it with a default, such as `getFlag("model", "quick")`. Existing remote config isn't converted automatically.
- Use the client's `track()` and `requestFeedback()` instead of the flag's.
- `setFlagOverride(key, value)` takes the value directly; pass `undefined` to remove an override.
- `getFlags()` returns all flag values and records a check for each.
- `getFlags()` returns all flag values and records a check for each. Replace `getFeatures()` and `getFeature(key)` with `getFlags()` and `getFlag(key)`; the feature-named methods are removed.
- Opt-in entries from `getOptInFlags()` have the flag's `value` instead of `isEnabled`.
- Remove `fallbackFlags` and pass a default to each read instead, such as `getFlag("huddles", true)`.
- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time.
- If you generate type declarations, regenerate them with the v2 CLI.
Expand Down
9 changes: 1 addition & 8 deletions packages/browser-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1151,13 +1151,6 @@ export class ReflagClient {
}, 1);
}

/**
* @deprecated Use `getFlags` instead.
*/
getFeatures() {
return this.getFlags();
}

/**
* Return direct values and register checks for these returned roots.
* Use getFlagResults() for diagnostic/serialization access without checks.
Expand Down Expand Up @@ -1217,7 +1210,7 @@ export class ReflagClient {
{
key,
...metadata,
isEnabled: flag.value === true,
value: flag.value,
} satisfies OptInFlag,
]
: [];
Expand Down
4 changes: 2 additions & 2 deletions packages/browser-sdk/src/flag/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ export type OptInFlag = RawFlagOptIn & {
key: string;

/**
* Result of flag evaluation.
* The flag's value for the current context, or `undefined` if it has none.
*/
isEnabled: boolean;
value: FlagValue | undefined;
};

export type EvaluationError = {
Expand Down
8 changes: 4 additions & 4 deletions packages/browser-sdk/test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ describe("bootstrap and opt-in boundaries", () => {
key: "flagA",
name: "Try it",
description: null,
isEnabled: true,
value: true,
userOptedIn: true,
companyOptedIn: false,
isOptedIn: true,
Expand Down Expand Up @@ -573,7 +573,7 @@ describe("bootstrap and opt-in boundaries", () => {
expect(client.getFlag("flagA")).toBe(false);
expect(client.getFlagsForBootstrap().flagStateVersion).toBe(2);
expect(client.getOptInFlags()).toEqual([
expect.objectContaining({ userOptedIn: true, isEnabled: false }),
expect.objectContaining({ userOptedIn: true, value: false }),
]);
expect(client.getIsLoadingOptInFlags()).toBe(false);
expect(request).toHaveBeenCalledOnce();
Expand Down Expand Up @@ -665,7 +665,7 @@ describe("bootstrap and opt-in boundaries", () => {
key: "flagA",
name: "Try",
description: null,
isEnabled: false,
value: false,
userOptedIn: false,
companyOptedIn: true,
isOptedIn: true,
Expand Down Expand Up @@ -774,7 +774,7 @@ describe("bootstrap and opt-in boundaries", () => {
expect(updated).toHaveReturnedWith([
expect.objectContaining({
key: "flagA",
isEnabled: override,
value: override,
userOptedIn: true,
}),
]);
Expand Down
2 changes: 1 addition & 1 deletion packages/node-sdk/src/edgeClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export type EdgeClientOptions = Omit<
* user: { id: "user-id" },
* company: { id: "company-id" },
* }
* const { isEnabled } = client.getFlag(context, "flag-key");
* const enabled = client.getFlag(context, "flag-key");
*
* ```
*/
Expand Down
8 changes: 5 additions & 3 deletions packages/react-native-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,7 @@ Render this component inside `ReflagProvider`.
## Opt-in hooks

```tsx
const { flags, isLoading } = useOptInFlags();
const setOptIn = useSetOptIn();
const { flags, isLoading, setOptIn } = useOptInFlags();
try {
const response = await setOptIn("huddles", { optedIn: true });
if (!response?.ok) console.error("Could not update opt-in");
Expand All @@ -188,7 +187,7 @@ try {
}
```

Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `useClient().refresh()` to retry.
Each entry includes the flag's `key`, `name`, `description` and `value`, and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `useClient().refresh()` to retry.

Pass `{ suspense: true }` to `useOptInFlags()` to suspend until the list loads. It defaults to the provider's `suspense` prop.

Expand All @@ -202,6 +201,9 @@ See the [Expo](https://github.com/reflagcom/javascript/tree/main/packages/react-
- Move remote config to a multivariate flag and read it with a default, such as `useFlag("model", "quick")`. Existing remote config isn't converted automatically.
- Use `useTrack()` instead of the flag's `track()`, and send feedback with `useSendFeedback()`.
- Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and the flag's loading property with `useIsLoading()`.
- `useFeature()` is removed. Use `useFlag()` instead.
- Use the `setOptIn` function returned by `useOptInFlags()`. `useSetOptIn()` still works but is deprecated.
- Opt-in entries have the flag's `value` instead of `isEnabled`.
- Remove `fallbackFlags` and pass a default to each read instead, such as `useFlag("huddles", true)`.
- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time.
- If you generate type declarations, regenerate them with the v2 CLI.
Expand Down
1 change: 0 additions & 1 deletion packages/react-native-sdk/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ const defaultEventSourceFactory: NonNullable<
export {
ReflagClientProvider,
useClient,
useFeature,
useFlag,
useFlagSuspense,
useIsLoading,
Expand Down
4 changes: 2 additions & 2 deletions packages/react-native-sdk/test/usage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ describe("React Native v2", () => {

test("loads opt-in metadata without replacing bootstrap values, then confirms v2 opt-in mutations", async () => {
let result: ReturnType<typeof useOptInFlags>;
let setOptIn: ReturnType<typeof useSetOptIn>;
let setOptIn: ReturnType<typeof useOptInFlags>["setOptIn"];
let enabled: boolean;
let changed = false;
fetchMock.mockImplementation(async (input, options) => {
Expand Down Expand Up @@ -592,7 +592,7 @@ describe("React Native v2", () => {
});
function Read() {
result = useOptInFlags();
setOptIn = useSetOptIn();
setOptIn = result.setOptIn;
enabled = useFlag("release");
return null;
}
Expand Down
6 changes: 1 addition & 5 deletions packages/react-native-sdk/type-tests/defaults.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import {
ReflagBootstrappedProvider,
ReflagProvider,
useFeature,
useFlag,
useFlagSuspense,
useOptInFlags,
useSetOptIn,
useTrack,
type BootstrappedFlags,
type FlagDefaultValue,
Expand All @@ -30,7 +28,6 @@ const state: BootstrappedFlags = {
export function NativeContracts() {
const enabled: boolean = useFlag("release");
const _undefinedDefault: boolean = useFlag("release", undefined);
const _legacyAlias: boolean = useFeature("release");
const _suspended: boolean = useFlagSuspense("release");
const _direct: Settings = useFlag("settings", settings);
const _ready: Settings = useFlagSuspense("settings", settings);
Expand All @@ -49,9 +46,8 @@ export function NativeContracts() {
mutable.limits.push(10);
const options: UseOptInFlagsOptions = { suspense: false };
const optIn: UseOptInFlagsResult = useOptInFlags(options);
const setOptIn = useSetOptIn();
for (const flag of optIn.flags)
void setOptIn(flag.key, { optedIn: !flag.userOptedIn });
void optIn.setOptIn(flag.key, { optedIn: !flag.userOptedIn });
const track = useTrack();
void track("Used native flag", { screen: "home" });
// @ts-expect-error Direct-value reads do not expose v1 wrappers.
Expand Down
5 changes: 2 additions & 3 deletions packages/react-native-sdk/type-tests/registered.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import {
useFlag,
useFlagSuspense,
useOptInFlags,
useSetOptIn,
type FlagKey,
type Flags as NativeFlags,
type FlagValue,
Expand Down Expand Up @@ -59,8 +58,8 @@ export function RegisteredNativeContracts() {
mutable.model = "quality";
mutable.prompt.tone = "detailed";
mutable.methods.push("express");
const setOptIn = useSetOptIn();
for (const flag of useOptInFlags().flags)
const { flags, setOptIn } = useOptInFlags();
for (const flag of flags)
void setOptIn(flag.key, { optedIn: !flag.userOptedIn });
// @ts-expect-error Registered keys constrain native reads.
useFlag("unknown");
Expand Down
8 changes: 5 additions & 3 deletions packages/react-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,7 @@ To use a client you create yourself, pass it to `ReflagClientProvider`. Your app
## Opt-in hooks

```tsx
const { flags, isLoading } = useOptInFlags();
const setOptIn = useSetOptIn();
const { flags, isLoading, setOptIn } = useOptInFlags();
try {
const response = await setOptIn("huddles", { optedIn: true });
if (!response?.ok) console.error("Could not update opt-in");
Expand All @@ -147,7 +146,7 @@ try {
}
```

Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `useClient().refresh()` to retry.
Each entry includes the flag's `key`, `name`, `description` and `value`, and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `useClient().refresh()` to retry.

Pass `{ suspense: true }` to `useOptInFlags()` to suspend until the list loads. It defaults to the provider's `suspense` prop.

Expand All @@ -157,6 +156,9 @@ Pass `{ suspense: true }` to `useOptInFlags()` to suspend until the list loads.
- Move remote config to a multivariate flag and read it with a default, such as `useFlag("model", "quick")`. Existing remote config isn't converted automatically.
- Use `useTrack()` and `useRequestFeedback()` instead of the flag's `track()` and `requestFeedback()`.
- Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and the flag's loading property with `useIsLoading()`.
- `useFeature()` is removed. Use `useFlag()` instead.
- Use the `setOptIn` function returned by `useOptInFlags()`. `useSetOptIn()` still works but is deprecated.
- Opt-in entries have the flag's `value` instead of `isEnabled`.
- Remove `fallbackFlags` and pass a default to each read instead, such as `useFlag("huddles", true)`.
- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time.
- If you generate type declarations, regenerate them with the v2 CLI.
Expand Down
32 changes: 26 additions & 6 deletions packages/react-sdk/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { deepEqual } from "fast-equals";
import React, {
createContext,
ReactNode,
useCallback,
useContext,
useEffect,
useLayoutEffect,
Expand Down Expand Up @@ -65,7 +66,7 @@ export type TypedFlags = keyof Flags extends never
* An opt-in-enabled flag for the generated React SDK flag definitions.
*
* Includes all fields from {@link @reflag/browser-sdk!OptInFlag}: `name`, `description`,
* `isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`.
* `value`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`.
* Only `key` is narrowed to the generated {@link FlagKey} type.
*/
export type OptInFlag = Omit<BrowserOptInFlag, "key"> & {
Expand Down Expand Up @@ -612,6 +613,19 @@ export type UseOptInFlagsResult = {
* Whether a bootstrapped provider is fetching opt-in metadata.
*/
isLoading: boolean;

/**
* Sets whether the current user or company has opted into a flag.
*
* Check the returned Response's `ok` property and catch promise rejections.
* HTTP failures return a non-OK Response; offline mode, invalid arguments, or
* missing scoped context return undefined. Confirmation failures can reject
* after the membership changed remotely. See {@link @reflag/browser-sdk!ReflagClient.setOptIn}.
*/
setOptIn: (
key: FlagKey,
options: SetOptInOptions,
) => Promise<Response | undefined>;
};

/** Boolean-first, non-suspending reads. Supply a positional default for JSON values. */
Expand Down Expand Up @@ -651,9 +665,6 @@ export function useFlagSuspense(
return useFlagValue(key, defaultValue, true);
}

/** @deprecated Use useFlag. */
export const useFeature = useFlag;

function useFlagValue(
key: FlagKey,
defaultValue: FlagDefaultValue,
Expand Down Expand Up @@ -698,7 +709,8 @@ function useFlagValue(
}

/**
* Returns opt-in-enabled flags and their loading state for the current context.
* Returns opt-in-enabled flags, their loading state, and a `setOptIn` function
* for the current context.
*
* The loading state is only used with `ReflagBootstrappedProvider` while
* opt-in metadata is fetched on demand. Regular providers load opt-in metadata
Expand Down Expand Up @@ -734,6 +746,12 @@ export function useOptInFlags(
setIsOptInFlagsLoading(client.getIsLoadingOptInFlags());
}, [client]);

const setOptIn = useCallback(
(key: FlagKey, optInOptions: SetOptInOptions) =>
client.setOptIn(String(key), optInOptions),
[client],
);

const suspense = options.suspense ?? context.suspense;
if (suspense && context.isLoading && isClientLoading(client)) {
throw context.getLoadingPromise();
Expand All @@ -744,12 +762,14 @@ export function useOptInFlags(
throw getOptInFlagsLoadingPromise(client);
}

return { flags, isLoading };
return { flags, isLoading, setOptIn };
}

/**
* Returns a function to set whether the current user or company has opted into a flag.
*
* @deprecated Use the `setOptIn` function returned by {@link useOptInFlags}.
*
* Check the returned Response's `ok` property and catch promise rejections.
* HTTP failures return a non-OK Response; offline mode, invalid arguments, or
* missing scoped context return undefined. Confirmation failures can reject
Expand Down
10 changes: 2 additions & 8 deletions packages/react-sdk/test/opt-in-types.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
useFlag,
useFlagSuspense,
useOptInFlags,
useSetOptIn,
} from "@reflag/react-sdk";
import { useFlag, useFlagSuspense, useOptInFlags } from "@reflag/react-sdk";

declare module "@reflag/react-sdk" {
interface Flags {
Expand All @@ -13,8 +8,7 @@ declare module "@reflag/react-sdk" {
}

export function GeneratedOptInTypes() {
const { flags } = useOptInFlags();
const setOptIn = useSetOptIn();
const { flags, setOptIn } = useOptInFlags();

for (const flag of flags) {
void setOptIn(flag.key, { optedIn: !flag.userOptedIn });
Expand Down
7 changes: 3 additions & 4 deletions packages/react-sdk/test/usage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ describe("opt-in hooks", () => {
await waitFor(() => expect(result.current.isLoading).toBe(false));
expect(result.current.flags[0]).toMatchObject({
key: "release",
isEnabled: true,
value: true,
userOptedIn: true,
});
});
Expand Down Expand Up @@ -735,7 +735,6 @@ describe("opt-in hooks", () => {
() => ({
value: useFlag("release"),
optIn: useOptInFlags(),
setOptIn: useSetOptIn(),
}),
{
wrapper: ({ children }) => (
Expand All @@ -748,14 +747,14 @@ describe("opt-in hooks", () => {
expect(result.current.optIn.flags[0].userOptedIn).toBe(false);
await act(async () => {
expect(
(await result.current.setOptIn("release", { optedIn: true }))?.ok,
(await result.current.optIn.setOptIn("release", { optedIn: true }))?.ok,
).toBe(true);
});
await waitFor(() =>
expect(result.current.optIn.flags[0].userOptedIn).toBe(true),
);
expect(result.current.value).toBe(false);
expect(result.current.optIn.flags[0].isEnabled).toBe(false);
expect(result.current.optIn.flags[0].value).toBe(false);
});

test("preserves opt-in Suspense and releases it after metadata failure", async () => {
Expand Down
Loading
Loading