Skip to content

Commit

Permalink
feat: add flagQueryFn to the context value (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
rqbazan authored Dec 7, 2021
1 parent ae74c7c commit b9df3ba
Showing 1 changed file with 36 additions and 30 deletions.
66 changes: 36 additions & 30 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export type FeatureProviderProps =

export interface FeatureContextValue {
cache: TCache
flagQueryFn: ReturnType<typeof createFlagQueryFn>
}

export const Op = {
Expand Down Expand Up @@ -50,34 +51,6 @@ export function createCache<F extends DefaultFeature = DefaultFeature>(features:
}, {} as Record<string, F>)
}

export function FeatureProvider(props: FeatureProviderProps) {
// @ts-expect-error
const { features, cache, children } = props

const contextValue = React.useMemo(() => {
return { cache: cache ?? createCache(features) }
}, [cache, features])

return <FeatureContext.Provider value={contextValue}>{children}</FeatureContext.Provider>
}

function useToggledContext() {
const contextValue = React.useContext(FeatureContext)

// @ts-ignore
if (contextValue === NO_PROVIDER) {
throw new Error('Component must be wrapped with FeatureProvider.')
}

return contextValue
}

export function useFeature(slug: string) {
const { cache } = useToggledContext()

return cache[slug]
}

export function createFlagQueryFn(cache: Record<string, DefaultFeature>) {
return function flagQueryFn(flagQuery: FlagQuery) {
if (typeof flagQuery === 'string') {
Expand Down Expand Up @@ -131,10 +104,43 @@ export function createFlagQueryFn(cache: Record<string, DefaultFeature>) {
}
}

export function useFlagQueryFn() {
export function FeatureProvider(props: FeatureProviderProps) {
// @ts-expect-error
const { features, cache, children } = props

const contextValue = React.useMemo(() => {
const _cache = cache ?? createCache(features)

return {
cache: _cache,
flagQueryFn: createFlagQueryFn(_cache),
}
}, [cache, features])

return <FeatureContext.Provider value={contextValue}>{children}</FeatureContext.Provider>
}

function useToggledContext() {
const contextValue = React.useContext(FeatureContext)

// @ts-ignore
if (contextValue === NO_PROVIDER) {
throw new Error('Component must be wrapped with FeatureProvider.')
}

return contextValue
}

export function useFeature(slug: string) {
const { cache } = useToggledContext()

return React.useMemo(() => createFlagQueryFn(cache), [cache])
return cache[slug]
}

export function useFlagQueryFn() {
const { flagQueryFn } = useToggledContext()

return flagQueryFn
}

export function useFlag(flagQuery: FlagQuery) {
Expand Down

0 comments on commit b9df3ba

Please sign in to comment.