Gathering detailed insights and metrics for @unleash/proxy-client-react
Gathering detailed insights and metrics for @unleash/proxy-client-react
Gathering detailed insights and metrics for @unleash/proxy-client-react
Gathering detailed insights and metrics for @unleash/proxy-client-react
npm install @unleash/proxy-client-react
85.5
Supply Chain
99
Quality
90.7
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
46 Stars
248 Commits
32 Forks
4 Watching
21 Branches
28 Contributors
Updated on 31 Oct 2024
Minified
Minified + Gzipped
TypeScript (96.05%)
JavaScript (3.95%)
Cumulative downloads
Total Downloads
Last day
-3.1%
23,946
Compared to previous day
Last week
3.9%
130,760
Compared to previous week
Last month
3%
558,726
Compared to previous month
Last year
95.9%
6,009,752
Compared to previous year
1npm install @unleash/proxy-client-react unleash-proxy-client 2# or 3yarn add @unleash/proxy-client-react unleash-proxy-client
Prepare Unleash Proxy secret or Frontend API Access token.
Import the provider like this in your entrypoint file (typically index.js/ts):
1import { createRoot } from 'react-dom/client'; 2import { FlagProvider } from '@unleash/proxy-client-react'; 3 4const config = { 5 url: '<unleash-url>/api/frontend', // Your front-end API URL or the Unleash proxy's URL (https://<proxy-url>/proxy) 6 clientKey: '<your-token>', // A client-side API token OR one of your proxy's designated client keys (previously known as proxy secrets) 7 refreshInterval: 15, // How often (in seconds) the client should poll the proxy for updates 8 appName: 'your-app-name', // The name of your application. It's only used for identifying your application 9}; 10 11const root = createRoot(document.getElementById('root')); 12 13root.render( 14 <React.StrictMode> 15 <FlagProvider config={config}> 16 <App /> 17 </FlagProvider> 18 </React.StrictMode> 19);
To connect this SDK to your Unleash instance's front-end API, use the URL to your Unleash instance's front-end API (<unleash-url>/api/frontend
) as the url
parameter. For the clientKey
parameter, use a FRONTEND
token generated from your Unleash instance. Refer to the how to create API tokens guide for the necessary steps.
To connect this SDK to the Unleash proxy, use the proxy's URL and a proxy client key. The configuration section of the Unleash proxy docs contains more info on how to configure client keys for your proxy.
To check if a feature is enabled:
1import { useFlag } from '@unleash/proxy-client-react'; 2 3const TestComponent = () => { 4 const enabled = useFlag('travel.landing'); 5 6 if (enabled) { 7 return <SomeComponent />; 8 } 9 return <AnotherComponent />; 10}; 11 12export default TestComponent;
To check variants:
1import { useVariant } from '@unleash/proxy-client-react'; 2 3const TestComponent = () => { 4 const variant = useVariant('travel.landing'); 5 6 if (variant.enabled && variant.name === 'SomeComponent') { 7 return <SomeComponent />; 8 } else if (variant.enabled && variant.name === 'AnotherComponent') { 9 return <AnotherComponent />; 10 } 11 return <DefaultComponent />; 12}; 13 14export default TestComponent;
useFlagsStatus retrieves the ready state and error events. Follow the following steps in order to delay rendering until the flags have been fetched.
1import { useFlagsStatus } from '@unleash/proxy-client-react'; 2 3const MyApp = () => { 4 const { flagsReady, flagsError } = useFlagsStatus(); 5 6 if (!flagsReady) { 7 return <Loading />; 8 } 9 return <MyComponent error={flagsError} />; 10};
Initial context can be specified on a FlagProvider
config.context
property.
<FlagProvider config={{ ...config, context: { userId: 123 }}>
This code sample shows you how to update the unleash context dynamically:
1import { useUnleashContext, useFlag } from '@unleash/proxy-client-react'; 2 3const MyComponent = ({ userId }) => { 4 const variant = useFlag('my-toggle'); 5 const updateContext = useUnleashContext(); 6 7 useEffect(() => { 8 // context is updated with userId 9 updateContext({ userId }); 10 }, [userId]); 11 12 // OR if you need to perform an action right after new context is applied 13 useEffect(() => { 14 async function run() { 15 // Can wait for the new flags to pull in from the different context 16 await updateContext({ userId }); 17 console.log('new flags loaded for', userId); 18 } 19 run(); 20 }, [userId]); 21};
By default, the Unleash client will start polling the Proxy for toggles immediately when the FlagProvider
component renders. You can prevent it by setting startClient
prop to false
. This is useful when you'd like to for example bootstrap the client and work offline.
Deferring the client start gives you more fine-grained control over when to start fetching the feature toggle configuration. This could be handy in cases where you need to get some other context data from the server before fetching toggles, for instance.
To start the client, use the client's start
method. The below snippet of pseudocode will defer polling until the end of the asyncProcess
function.
1const client = new UnleashClient({ 2 /* ... */ 3}); 4 5const MyAppComponent = () => { 6 useEffect(() => { 7 const asyncProcess = async () => { 8 // do async work ... 9 client.start(); 10 }; 11 asyncProcess(); 12 }, []); 13 14 return ( 15 // Pass client as `unleashClient` and set `startClient` to `false` 16 <FlagProvider unleashClient={client} startClient={false}> 17 <App /> 18 </FlagProvider> 19 ); 20};
1import { useUnleashContext, useUnleashClient } from '@unleash/proxy-client-react' 2 3const MyComponent = ({ userId }) => { 4 const client = useUnleashClient(); 5 6 const login = () => { 7 // login user 8 if (client.isEnabled("new-onboarding")) { 9 // Send user to new onboarding flow 10 } else ( 11 // send user to old onboarding flow 12 ) 13 } 14 15 return <LoginForm login={login}/> 16}
Since this library uses hooks you have to implement a wrapper to use with class components. Beneath you can find an example of how to use this library with class components, using a custom wrapper:
1import React from 'react'; 2import { 3 useFlag, 4 useUnleashClient, 5 useUnleashContext, 6 useVariant, 7 useFlagsStatus, 8} from '@unleash/proxy-client-react'; 9 10interface IUnleashClassFlagProvider { 11 render: (props: any) => React.ReactNode; 12 flagName: string; 13} 14 15export const UnleashClassFlagProvider = ({ 16 render, 17 flagName, 18}: IUnleashClassFlagProvider) => { 19 const enabled = useFlag(flagName); 20 const variant = useVariant(flagName); 21 const client = useUnleashClient(); 22 23 const updateContext = useUnleashContext(); 24 const { flagsReady, flagsError } = useFlagsStatus(); 25 26 const isEnabled = () => { 27 return enabled; 28 }; 29 30 const getVariant = () => { 31 return variant; 32 }; 33 34 const getClient = () => { 35 return client; 36 }; 37 38 const getUnleashContextSetter = () => { 39 return updateContext; 40 }; 41 42 const getFlagsStatus = () => { 43 return { flagsReady, flagsError }; 44 }; 45 46 return ( 47 <> 48 {render({ 49 isEnabled, 50 getVariant, 51 getClient, 52 getUnleashContextSetter, 53 getFlagsStatus, 54 })} 55 </> 56 ); 57};
Wrap your components like so:
1<UnleashClassFlagProvider 2 flagName="demoApp.step1" 3 render={({ isEnabled, getClient }) => ( 4 <MyClassComponent isEnabled={isEnabled} getClient={getClient} /> 5 )} 6/>
IMPORTANT: This no longer comes included in the unleash-proxy-client-js library. You will need to install the storage adapter for your preferred storage solution.
Because React Native doesn't run in a web browser, it doesn't have access to the localStorage
API. Instead, you need to tell Unleash to use your specific storage provider. The most common storage provider for React Native is AsyncStorage.
To configure it, add the following property to your configuration object:
1const config = {
2 storageProvider: {
3 save: (name, data) => AsyncStorage.setItem(name, JSON.stringify(data)),
4 get: async (name) => {
5 const data = await AsyncStorage.getItem(name);
6 return data ? JSON.parse(data) : undefined;
7 },
8 },
9};
If you were previously using the built in Async storage used in the unleash-proxy-client-js, this no longer comes bundled with the library. You will need to install the storage adapter for your preferred storage solution. Otherwise there are no breaking changes.
Previously the unleash client was bundled as dependency directly in this library. It's now changed to a peer dependency and listed as an external.
In v2 there was only one distribution based on the fact that webpack polyfilled the necessary features in v4. This is no longer the case in webpack v5. We now provide two distribution builds, one for the server and one for the client - and use the browser field in the npm package to hint module builders about which version to use. The default dist/index.js
file points to the node version, while the web build is located at dist/index.browser.js
Upgrading should be as easy as running yarn again with the new version, but we made the made bump regardless to be safe. Note: If you are not able to resolve the peer dependency on unleash-proxy-client
you might need to run npm install unleash-proxy-client
startClient
option has been simplified. Now it will also work if you don't pass custom client with it. It defaults to true
.
The major release is driven by Node14 end of life and represents no other changes. From this version onwards we do not guarantee that this library will work server side with Node 14.
This feature flag SDK is designed according to our design philosophy. You can read more about that here.
No vulnerabilities found.
No security vulnerabilities found.