|
| 1 | +import { initialize } from '@launchdarkly/js-client-sdk'; |
| 2 | + |
| 3 | +// Set clientSideID to your LaunchDarkly client-side ID |
| 4 | +const clientSideID = 'LD_CLIENT_SIDE_ID'; |
| 5 | + |
| 6 | +// Set flagKey to the feature flag key you want to evaluate |
| 7 | +const flagKey = 'LD_FLAG_KEY'; |
| 8 | + |
| 9 | +// Set up the evaluation context. This context should appear on your |
| 10 | +// LaunchDarkly contexts dashboard soon after you run the demo. |
| 11 | +const context = { |
| 12 | + kind: 'user', |
| 13 | + key: 'example-user-key', |
| 14 | + name: 'Sandy', |
| 15 | +}; |
| 16 | + |
| 17 | +const div = document.createElement('div'); |
| 18 | +const statusBox = document.createElement('div'); |
| 19 | + |
| 20 | +document.body.appendChild(statusBox); |
| 21 | +document.body.appendChild(div); |
| 22 | + |
| 23 | +div.appendChild(document.createTextNode('No flag evaluations yet')); |
| 24 | +statusBox.appendChild(document.createTextNode('Initializing...')); |
| 25 | + |
| 26 | +const main = async () => { |
| 27 | + const ldclient = initialize(clientSideID); |
| 28 | + const render = () => { |
| 29 | + const flagValue = ldclient.variation(flagKey, false); |
| 30 | + const label = `The ${flagKey} feature flag evaluates to ${flagValue}.`; |
| 31 | + document.body.style.background = flagValue ? '#00844B' : '#373841'; |
| 32 | + div.replaceChild(document.createTextNode(label), div.firstChild as Node); |
| 33 | + }; |
| 34 | + |
| 35 | + ldclient.on('error', () => { |
| 36 | + statusBox.replaceChild( |
| 37 | + document.createTextNode('Error caught in client SDK'), |
| 38 | + statusBox.firstChild as Node, |
| 39 | + ); |
| 40 | + }); |
| 41 | + |
| 42 | + // Listen for flag changes |
| 43 | + ldclient.on('change', () => { |
| 44 | + render(); |
| 45 | + }); |
| 46 | + |
| 47 | + const { status } = await ldclient.identify(context); |
| 48 | + |
| 49 | + if (status === 'completed') { |
| 50 | + statusBox.replaceChild(document.createTextNode('Initialized'), statusBox.firstChild as Node); |
| 51 | + } else if (status === 'error') { |
| 52 | + statusBox.replaceChild( |
| 53 | + document.createTextNode('Error identifying client'), |
| 54 | + statusBox.firstChild as Node, |
| 55 | + ); |
| 56 | + } |
| 57 | + |
| 58 | + render(); |
| 59 | +}; |
| 60 | + |
| 61 | +main(); |
0 commit comments