npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

flagsmith-react

v1.2.4

Published

Flagsmith integration for React Single Page Applications (SPA)

Downloads

3,320

Readme

flagsmith-react

Flagsmith SDK for React Single Page Applications (SPA).

npm version Known Vulnerabilities CI Action Maintainability Coverage Status

Contents

Installation

Using npm

npm install flagsmith-react

Using yarn

yarn add flagsmith-react

Getting Started

Configure the SDK by wrapping your application in a FlagsmithProvider element:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {FlagsmithProvider} from 'flagsmith-react';
import App from './App';

ReactDOM.render(
    <FlagsmithProvider
        environmentId="YOUR_FLAGSMITH_ENVIRONMENT_ID"
    >
        <App />
    </FlagsmithProvider>,
    document.getElementById('app')
);

The Flagsmith Provider defaults to using the vanilla JavaScript Flagsmith SDK. To support alternative SDK, for example the React Native variant, a specific provider can be supplied as a parameter, for example

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {FlagsmithProvider} from 'flagsmith-react';
import flagsmith from 'react-native-flagsmith';
import App from './App';

ReactDOM.render(
    <FlagsmithProvider
        environmentId="YOUR_FLAGSMITH_ENVIRONMENT_ID"
        flagsmith={ flagsmith }
    >
        <App />
    </FlagsmithProvider>,
    document.getElementById('app')
);

Use the useFlagsmith hook in your components to access the Flagsmith state (isLoading, isIdentified, isError) and feature flag and remote configuration methods (hasFeature, getValue etc.)

import React from 'react';
import { useFlagsmith } from 'flagsmith-react';

function App() {
    const {
        isLoading,
        isError,
        hasFeature,
        getValue
    } = useFlagsmith();

    if (isLoading) {
        return <div>Flagsith state is loading...</div>
    }

    if (isError) {
        return <div>Failed to load Flagsmith state!</div>
    }

    const hasExtraText = hasFeature('extra_text')
    const theValue = getValue('example_value')

    return <div>
        <div>The value is {theValue}.</div>
        {
            hasExtraText && <div>Here is the extra text feature</div>
        }
    </div>
}

export default App;

API Reference

The flagsmith-react API is modelled on the Flagsmith Javascript integration, the documentation for which can be found here for further reference.

FlagsmithProvider

  <FlagsmithProvider 
    environmentId
    flagsmith
    asyncStorage
    cacheFlags
    defaultFlags
    preventFetch
    api>
  </FlagsmithProvider>

Use the FlagsmithProvider component to wrap your application and allow child elements to access the Flagsmith functionality using the 'useFlagsmith' hook function.

useFlagsmith

const {
    isLoading,
    isIdentified,
    isError,
    identify,
    hasFeature,
    getValue,
    subscribe
} = useFlagsmith();

Use the useFlagsmith hook in your components to access the Flagsmith state and methods.

isLoading: boolean

True if the Flagsmith state is loading, false is the state is loaded and usable. You should not try accessing the state (i.e. feature flags and remote configuration) until this is false and the state is loaded.

isIdentified: boolean

True if Flagsmith has been configured to use a specific identity when resolving flags and remote configuration, false otherwise.

See identify for more information.

isListening: boolean

True if Flagsmith is configured to listen for updates. See startListening for more details.

isError: boolean

True if the Flagsmith integration is in an errored state (e.g. the server could not be reached). False otherwise.

identify

await identify(identity)

Passes the supplied identity to the Flagsmith backend to be used when resolving feature flags and remote configuration. This causes an update in the state, which is an async action. Use the isIdentified flag to determine when the state has been re-loaded, or use subscribe to receive an update notification.

logout

await logout()

Remove any identity associated with the Flagsmith client. Use the isIdentified flag to determine when the state has been re-loaded, or use subscribe to receive an update notification.

hasFeature

hasFeature(key)

Determines is the feature specified key is set or not.

getValue

getValue(key)

Gets the current value of the remote configuration item specified by the key.

startListening

startListening(interval = 1000)

Begin listening for backend configuration changes. The polling interval is specified in mS. Use isListening to determine the current listening state, and subscribe to be notified of updates.

stopListening

stopListening()

Stop listening (polling) for configuration changes.

subscribe

subscribe(callback)

Registers a callback with Flagsmith that will be triggered any time a new configuration is available, for example after loading is complete, or when a new user is identified. This can be used to update any configuration state in components using Flagsmith, per the following example.

import { useEffect, useState } from 'react'
import logo from './logo.svg';
import './App.css';
import { useFlagsmith } from 'flagsmith-react'

function App() {
  const { isLoading, isError, getValue, identify, subscribe } = useFlagsmith()
  const [val, setVal] = useState()

  useEffect(() => {
    if(!isLoading) {
      identify('[email protected]')
    }
  }, [isLoading, identify])

  const handleChange = () => {
    setVal( getValue('val') )
  }

  subscribe(handleChange)

  return (
    <>
      {
        !isLoading &&
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <p>
              Edit <code>src/App.js</code> and save to reload.
            </p>
            <a
              className="App-link"
              href="https://reactjs.org"
              target="_blank"
              rel="noopener noreferrer"
            >
              Learn React
            </a>
            {
              isError && <h3>Flagsmith failed to load</h3>
            }
            {
              val && <h1>{val}</h1>
            }
          </header>
        </div>
      }
    </>
  );
}

export default App;

getFlags

await getFlags()

Forces a fetch of the current flags.

getTrait

getTrait(key)

Can only be used once a user has been identified, to get the value of the specified trait for that user.

setTrait

await setTrait(key, value)

Can only be used once a user has been identified, to set the value of the specified trait for that user.

setTraits

await setTraits(traits)

Can only be used once a user has been identified, to set the value of the multiple traits for that user. Traits set to a value of null will be removed.

incrementTrait

await incrementTrait(key, incrementBy)

Can only be used once a user has been identified, used to increment (or decrement) the specified trait for that user.