🚀 DAY 5 OF LAUNCH WEEK:Introducing Webhook Events for Alert Changes.Learn more →
Socket
Book a DemoInstallSign in
Socket

@unleash/proxy-client-react

Package Overview
Dependencies
Maintainers
4
Versions
77
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@unleash/proxy-client-react

React interface for working with unleash

Source
npmnpm
Version
2.0.0
Version published
Weekly downloads
236K
0.77%
Maintainers
4
Weekly downloads
 
Created
Source

DISCLAIMER:

This library is meant to be used with the unleash-proxy. The proxy application layer will sit between your unleash instance and your client applications, and provides performance and security benefits. DO NOT TRY to connect this library directly to the unleash instance, as the datasets follow different formats because the proxy only returns evaluated toggle information.

Installation

npm install @unleash/proxy-client-react
// or
yarn add @unleash/proxy-client-react

Upgrade path from v1 -> v2

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.

Initialization

Import the provider like this in your entrypoint file (typically index.js/ts):

import FlagProvider from '@unleash/proxy-client-react';

const config = {
  url: 'https://HOSTNAME/proxy',
  clientKey: 'PROXYKEY',
  refreshInterval: 15,
  appName: 'your-app-name',
  environment: 'dev',
};

ReactDOM.render(
  <React.StrictMode>
    <FlagProvider config={config}>
      <App />
    </FlagProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

Alternatively, you can pass your own client in to the FlagProvider:

import FlagProvider, { UnleashClient } from '@unleash/proxy-client-react';

const config = {
  url: 'https://HOSTNAME/proxy',
  clientKey: 'PROXYKEY',
  refreshInterval: 15,
  appName: 'your-app-name',
  environment: 'dev',
};

const client = new UnleashClient(config);

ReactDOM.render(
  <React.StrictMode>
    <FlagProvider unleashClient={client}>
      <App />
    </FlagProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

Deferring client start

By default, the Unleash client will start polling the Proxy for toggles immediately when the FlagProvider component renders. You can delay the polling by:

  • setting the startClient prop to false
  • passing a client instance to the FlagProvider
ReactDOM.render(
  <React.StrictMode>
    <FlagProvider unleashClient={client} startClient={false}>
      <App />
    </FlagProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

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.

const client = new UnleashClient({ /* ... */ })

useEffect(() => {
    const asyncProcess = async () => {
	// do async work ...
	client.start()
    }
    asyncProcess()
  }, [])

return (
  // Pass client as `unleashClient` and set `startClient` to `false`
  <FlagProvider unleashClient={client} startClient={false}>
    <App />
  </FlagProvider>
)

Usage

Check feature toggle status

To check if a feature is enabled:

import { useFlag } from '@unleash/proxy-client-react';

const TestComponent = () => {
  const enabled = useFlag('travel.landing');

  if (enabled) {
    return <SomeComponent />
  }
  return <AnotherComponent />
};

export default TestComponent;

Check variants

To check variants:

import { useVariant } from '@unleash/proxy-client-react';

const TestComponent = () => {
  const variant = useVariant('travel.landing');

  if (variant.enabled && variant.name === "SomeComponent") {
    return <SomeComponent />
  } else if (variant.enabled && variant.name === "AnotherComponent") {
    return <AnotherComponent />
  }
  return <DefaultComponent />
};

export default TestComponent;

Defer rendering until flags fetched

useFlagsStatus retrieves the ready state and error events. Follow the following steps in order to delay rendering until the flags have been fetched.

import { useFlagsStatus } from '@unleash/proxy-client-react'

const MyApp = () => {
  const { flagsReady, flagsError } = useFlagsStatus();

  if (!flagsReady) {
    return <Loading />
  }
  return <MyComponent error={flagsError}/>
}

Updating context

Follow the following steps in order to update the unleash context:

import { useUnleashContext, useFlag } from '@unleash/proxy-client-react'

const MyComponent = ({ userId }) => {
  const variant = useFlag("my-toggle");
  const updateContext = useUnleashContext();

  useEffect(() => {
    // context is updated with userId
    updateContext({ userId })
  }, [userId])

  useEffect(() => {
    async function run() {
    // Can wait for the new flags to pull in from the different context
      await updateContext({ userId });
      console.log('new flags loaded for', userId);
    }
    run();
  }, [userId]);
}

React Native

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:

const config = {
  storageProvider: {
    save: (name, data) => AsyncStorage.setItem(name, JSON.stringify(data)),
    get: async (name) => {
      const data = await AsyncStorage.getItem(name);
      return data ? JSON.parse(data) : undefined;
    }
  },
};

FAQs

Package last updated on 20 Apr 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts