-
-
Save orderedlist/15ef81897df209a35c464e13baf0f6b8 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
// App.jsx | |
// import React from 'react' | |
// import FlipperContextProvider from './contexts/FlipperContextProvider' | |
// import List from './components/List' | |
// function App() { | |
// return ( | |
// <FlipperContextProvider> | |
// <List /> | |
// </FlipperContextProvider> | |
// ) | |
// } | |
// List.jsx | |
// import React from 'react' | |
// import { useFlipper } from '@/contexts/FlipperContextProvider' | |
// export default function List() { | |
// const { isEnabled } = useFlipper() | |
// return ( | |
// <div> | |
// <h1>Feature Flags</h1> | |
// <p>Feature 1: {isEnabled('feature1') ? 'enabled' : 'disabled'}</p> | |
// <p>Feature 2: {isEnabled('feature2') ? 'enabled' : 'disabled'}</p> | |
// <p>Feature 3: {isEnabled('feature3') ? 'enabled' : 'disabled'}</p> | |
// </div> | |
// ) | |
// } | |
import React, { useContext, useState, useEffect, createContext } from "react"; | |
const FlipperContext = createContext(); | |
function FlipperContextProvider({ children }) { | |
// Initialize state | |
const [features, setFeatures] = useState({}) | |
const [isLoading, setIsLoading] = useState(true) | |
// Fetch data | |
useEffect(async () => { | |
const response = await fetch("/flipper.json") | |
const data = await response.json() | |
setFeatures(data) | |
setIsLoading(false) | |
}, []); | |
return ( | |
<FlipperContext.Provider value={{ features }} loading={isLoading}> | |
{children} | |
</FlipperContext.Provider> | |
); | |
} | |
export default FlipperContextProvider; | |
export function useFlipper() { | |
const context = useContext(FlipperContext); | |
if (context === undefined) { | |
throw new Error("Context must be used within a Provider"); | |
} | |
const isEnabled = (feature, defaultValue = false) => { | |
return context.features[feature] ?? defaultValue | |
} | |
return { isEnabled }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment