launchdarkly / react-client-sdk

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

Using asyncWithLDProvider in a functional component #93

Closed robbienohra closed 3 years ago

robbienohra commented 3 years ago

Is your feature request related to a problem? Please describe. I'd like to use asyncWithLDProvider in a functional component, but not entirely sure what the cleanest way to do this is. I've tried introducing state to hold the LDProvider component in state and initialize it in a useEffectbut I'm having difficulty working with the FunctionComponent type returned in the promise of the asyncWithLDProvider HOC.

Describe the solution you'd like It would be really appreciated if a working example of using asyncWithLDProvider in a functional component was provided.

ctawiah commented 3 years ago

Hi @robbienohra, see an example below - you can find additional examples here. For additional information about how to use asyncWithLDProvider please refer to our docs.

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { asyncWithLDProvider, useFlags } from 'launchdarkly-react-client-sdk';

const clientSideID = 'YOUR_CLIENT_SIDE_ID_HERE';

const App = () => {
  const flags = useFlags();

  return <div>This is a test from function component: My flag is {flags.exampleTest ? 'ON' : 'OFF'}</div>
}

const renderApp = async () => {
  const LDProvider = await asyncWithLDProvider({ clientSideID });

  ReactDOM.render(
    <React.StrictMode>
      <LDProvider>
        <App />
      </LDProvider>
    </React.StrictMode>,
    document.getElementById('root')
  )
}

renderApp();
robbienohra commented 3 years ago

@ctawiah thanks for the response — I don't think this is entirely satisfactory though 🤔 Since you're still relying on calling ReactDOM.render as opposed to having an e2e functional setup

ctawiah commented 3 years ago

@robbienohra I understood your question as requesting an example of how to use the asyncWithLDProvider provider in a react web application using function components. In the example I shared, App is a function component wrapped by LDProvider, this way the component can call useFlags hook which uses the LDProvider context.

can you provide clarification on what you meant by

relying on calling ReactDOM.render as opposed to having an e2e functional setup

or share additional information about your request? Thanks