launchdarkly / react-client-sdk

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

Multiple instances of library in a single application. #230

Closed nxp769 closed 10 months ago

nxp769 commented 10 months ago

Is this a support request? Yes

Describe the bug I have 2 React JS applications and I call one as a "Host" and another one is "Child"(which is a npm module itself.). I want to configure LDProvider in "Host" app and the child app should be able to fetch those flags using useFlags custom hook. I added "launchdarkly-react-client-sdk": "^3.0.9" under peerDependencies of "Child" module and the same under dependencies of "Host" application. Here "Child" will be dependency for "Host" application. As I includedthe "launchdarkly-react-client-sdk" under peerDependencies of "Child" module, Ideally "Host" and "Child" should share the same instance of "launchdarkly-react-client-sdk" library, but it is not happening in this way. When my "Child" tried to call useFlags hooks I am getting empty object but when I use the same hook in "Host" app I could see the available flags configured. This means that both "Host" and "Child" are pointing to a different instance of "launchdarkly-react-client-sdk" library and unable to access the same context to fetch the flags.

FYI I am using many other modules in the same way as I am doing for "launchdarkly-react-client-sdk" library and did not face any issues with them.

To reproduce Steps to reproduce the behavior.

  1. Create two react applications called "Host" and "Child".
  2. Make "child" as an npm module and add this module as a dependency to "Host" app.
  3. Add "launchdarkly-react-client-sdk" under peerDependencies of "Child" module.
  4. Add "launchdarkly-react-client-sdk" under dependencies of "Host" application.
  5. Configure LDProvider on the "Host" application.
  6. Try to access flags in "Child" module using "useFlags" custom hooks of "launchdarkly-react-client-sdk" library

Expected behavior Flags should be accessible even by child module as the context is same.

Logs If applicable, add any log output related to your problem.

SDK version "launchdarkly-react-client-sdk": "^3.0.9",

Language version, developer tools Node v18.1.0 Yalc: for local package development

OS/platform Windows 10 Chrome browser

Additional context Add any other context about the problem here.

nxp769 commented 10 months ago

Finally found a fix for this.

Child module is picking the launchdarkly-react-client-sdk from ./lib/cjs/index.js and host is picking from ./lib/esm/index.js. Forcing both Host and child to use ./lib/cjs/index.js by changing import to require solved the issue.