Created
March 4, 2020 16:46
-
-
Save sebastian-schlecht/f1a2e3c7990460c4e29647a072409569 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const withFeatureFlag = (featureFlag: string, defaultValue: boolean) => <P extends object>( | |
Component: React.ComponentType<P>, | |
) => { | |
interface WithFeatureFlagProps { | |
[featureFlag: string]: boolean | undefined; | |
} | |
const WithFeatureFlag: React.FC<P & WithFeatureFlagProps> = props => { | |
const [flag, setFlag] = useState<boolean>(defaultValue); | |
// Initial query for feature flag | |
useEffect(() => { | |
const listener = (flag: string) => { | |
if (flag === featureFlag) { | |
launchDarklyClient | |
.jsonVariation(featureFlag, defaultValue) | |
.then((value: boolean) => setFlag(value)); | |
} | |
}; | |
// Register change listener | |
launchDarklyClient.jsonVariation(featureFlag, defaultValue).then((value: any) => { | |
setFlag(value); | |
launchDarklyClient.registerFeatureFlagListener(featureFlag, listener); | |
}); | |
// Cleanup | |
return () => { | |
launchDarklyClient.unregisterFeatureFlagListener(featureFlag, listener); | |
}; | |
}, []); | |
return <Component {...(props as P)} {...{ [featureFlag]: flag }} />; | |
}; | |
return WithFeatureFlag; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment