launchdarkly / react-client-sdk

LaunchDarkly Client-side SDK for React.js
Other
85 stars 68 forks source link

Access flags without provider #74

Closed grug closed 3 years ago

grug commented 3 years ago

Hi there - this might be a silly question, but is it possible to access flags without needing hooks? I need to access flags at a point in my application before the React application is actually instantiated (it's to control whether or not to register a service worker). Any help is appreciated :)

ctawiah commented 3 years ago

Hi @grug, I believe you can use our javascript client sdk to achieve this, you can read the documentation here. Our react-client-sdk actually uses the launchdarkly-js-client-sdk under the hood. For your use case, you can explore the example approach below:

import * as LDClient from 'launchdarkly-js-client-sdk';

const ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', { anonymous: true });

const renderApp = () => (
  ReactDOM.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
    document.getElementById('root')
  )
)

ldclient.on('ready', () => {
  const registerWorker = ldclient.variation("YOUR_FEATURE_KEY", false);

  if (registerWorker) {
    // init worker
  } else {
    renderApp();
  }
});

ldclient.on('change', function(flags) {
  console.log('flags changed:', flags);
  // add your feature behavior here...
});

Hope this helps.

grug commented 3 years ago

Hey @ctawiah I'll give this a go today and let you know how it goes :) I really appreciate you responding to me!

ctawiah commented 3 years ago

Hi @grug, i'm going to close this issue for now, please re-open it or create a new one if you run into any additional issues. Thanks.