Last active
April 18, 2023 20:44
-
-
Save robwierzbowski/3852ddeef434504fd8a4ab5be100522c to your computer and use it in GitHub Desktop.
Solution
This file contains hidden or 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
import { useEffect, useState } from 'react'; | |
// returns the state of *all* features for current user | |
const fetchAllFeatures = () => | |
// in reality, this would have been a `fetch` call: | |
// `fetch("/api/features/all")` | |
// Executes once | |
// console.log('fetch called'); | |
new Promise(resolve => { | |
console.log('This is logged once'); | |
const sampleFeatures = { | |
'extended-summary': true, | |
'feedback-dialog': false, | |
}; | |
setTimeout(resolve, 100, sampleFeatures); | |
}); | |
// Module begins here | |
let featureStore = {}; | |
// Store the resolving fetch so every call to getFeatureState can | |
// reference this single promise | |
let fetchingAllFeatures; | |
const getFeatureState = async feature => { | |
if (!fetchingAllFeatures) { | |
fetchingAllFeatures = fetchAllFeatures(); | |
} | |
featureStore = await fetchingAllFeatures; | |
return featureStore[feature] || false; | |
}; | |
const App = () => { | |
const [summaryEnabled, setSummaryEnabled] = useState(undefined); | |
const [feedbackDialogEnabled, setFeedbackDialogEnabled] = useState(undefined); | |
useEffect(() => { | |
getFeatureState('extended-summary').then(featureState => { | |
setSummaryEnabled(featureState); | |
}); | |
}, []); | |
useEffect(() => { | |
getFeatureState('feedback-dialog').then(featureState => { | |
setFeedbackDialogEnabled(featureState); | |
}); | |
}, []); | |
return ( | |
<> | |
<div>Summary is enabled: {`${summaryEnabled}`}</div> | |
<div>Summary is enabled: {`${feedbackDialogEnabled}`}</div> | |
</> | |
); | |
}; | |
export { App }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment