@mysense/feature-flagsdeprecated

Feature flags react client sdk

Usage no npm install needed!

<script type="module">
  import mysenseFeatureFlags from 'https://cdn.skypack.dev/@mysense/feature-flags';
</script>

README

Feature Flags React SDK

Getting started

yarn add @mysense/feature-flags

Setup Provider

Create provider with a storage adapter relevant to your environment.

import { set, get } from 'idb-keyval';
import { StorageAdapter, createFeatureFlagsProvider } from '@mysense/feature-flags';

const storageAdapter: StorageAdapter = {
  set(key, value) {
    return set(key, value);
  },
  get(key) {
    return get(key);
  },
};

const FeatureFlagsProvider = createFeatureFlagsProvider(storageAdapter);

export default FeatureFlagsProvider;

Wrap your app with <FeatureFlagsProvider />, which makes the feature client and flags state available to the rest of your app.

import React from 'react';
import ReactDOM from 'react-dom';
import { FeatureFlagsProvider } from 'path/to/fetureFlagsProvider';
import App from './App';

const rootElement = document.getElementById('root');

ReactDOM.render(
  <FeatureFlagsProvider>
    <App />
  </FeatureFlagsProvider>,
  rootElement
);

Initialize client

This signals to the provider that flags are ready to be fetched for a particular user, and configs it according to whatever options you provide it. Do this once you've completed authentication and have access to uid.

import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useFeatureClient } from '@mysense/feature-flags';

type FeatureClientOptions = {
  polling?: boolean;
  persist?: boolean;
};

function Home() {
  // Already authenticated and have fetched uid.
  const uid = useSelector((state) => state.userAttributes.sub);
  const { init } = useFeatureClient;

  useEffect(() => {
    const options: FeatureClientOptions = {
      polling: true,
      persist: true,
    }

    init(uid, options);
  }, [])

  return <h1>Home</h1>;
}

Since other user context can be fetched from consumerInfo table, all we need to currently provide is uid. We can expand on this in future iterations if needed. Polling is set at 15min intervals, and persist will store fetched flags in IndexedDB for web and AsyncStorage for React-Native.

Use flags

Once you've initialized successfully, flags will be made available via useFlags hook. If you need to set default values for undefined flags, you can do so via destructuring and default parameters. feature ids are automatically converted to camel case on client side.

import React, { useEffect } from 'react';
import { useFlags } from '@mysense/feature-flags';

function Profile() {
  const { booleanFeature, numOrStringFeature = 'blue' } = useFlags;

  return (
    {booleanFeature && <h1>Hello World</h1>}
    {numOrStringFeature === 'blue' ? 
      <h1>Blue header</h1>
      : numOrStringFeature === 'yellow' ? 
          <h1>Yellow header</h1>
          : <h1>Plain header</h1>
    }
  )
}