javascriptreactjsfeaturetogglelaunchdarkly

Implement Launchdarkly with function in react without wrapping in Component


Currently I am following the guidelines provided by launchdarkly and as per documentation I used:

import { asyncWithLDProvider } from 'launchdarkly-react-client-sdk';
(async () => {
  const LDProvider = await asyncWithLDProvider({
    clientSideID: 'CLIENT_SIDE_ID',
    context: {
      "kind": "user",
      "key": "KEY",
      "name": "NAME",
      "email": "abc@example.com"
    },
  });
  render(
    <LDProvider>
      <ControllerPage />
    </LDProvider>,
    document.getElementById('reactDiv'),
  );
})();

This somehow create problem as it's not working properly .

Also this is not my requirement even if it work I don't want to wrap my read code with <LDProvider></LDProvider>. So i am asking is there any solution for this problem that I can use launchdarkly implementation using function without Wrapping my code with <LDProvider></LDProvider> .


Solution

  • This can be easily done as :

    NPM Package :

    npm install launchdarkly-js-client-sdk
    

    Code :

    import * as LDClient from 'launchdarkly-js-client-sdk';
    
    const randomString = Math.random().toString(36).slice(2)
    const newUser = {
        "kind": "user",
        "key": `guest-user-${randomString}`,
        "name": `guest-user-${randomString}`,
        "email": `guest-user-${randomString}@email.com`
    }
    const ldclient = await LDClient.initialize('LAUNCHDARKLY_ID', newUser);
    ldclient.on("ready", () => {
        const flagData = ldclient.allFlags();
        const flagResponse = flagData['feature_name']
        if (flagResponse != undefined && flagResponse) {
            //  Do this
        }else{
            // Do this
        }
    

    Above code is used to evaluates all the flags. If you want to evaluate a particular flag then it would be like this :

    import * as LDClient from 'launchdarkly-js-client-sdk';
    
    const randomString = Math.random().toString(36).slice(2)
    const newUser = {
        "kind": "user",
        "key": `guest-user-${randomString}`,
        "name": `guest-user-${randomString}`,
        "email": `guest-user-${randomString}@email.com`
    }
    const ldclient = await LDClient.initialize('LAUNCHDARKLY_ID', newUser);
    ldclient.on("ready", () => {
        const flagResponse = ldclient.variation('flag-key-123abc',false);
        if (flagResponse != undefined && flagResponse) {
            //  Do this
        }else{
            // Do this
        }
    

    Above , false represents if somehow error occurred then what would be the default value one should use.