Skip to content

Commit

Permalink
fix(core): update featuresEnabled when switching projects
Browse files Browse the repository at this point in the history
  • Loading branch information
pedrobonamin committed Feb 19, 2024
1 parent 86bf2e9 commit 905e811
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions packages/sanity/src/core/hooks/useFeatureEnabled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {useMemoObservable} from 'react-rx'
import {type Observable, of} from 'rxjs'
import {catchError, map, shareReplay, startWith} from 'rxjs/operators'

import {useSource} from '../studio'
import {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../studioClient'
import {useClient} from './useClient'

Expand All @@ -28,26 +29,28 @@ function fetchFeatures({versionedClient}: {versionedClient: SanityClient}): Obse
})
}

let cachedFeatureRequest: Observable<string[]>
const cachedFeatureRequest = new Map<string, Observable<string[]>>()

/** @internal */
export function useFeatureEnabled(featureKey: string): Features {
const versionedClient = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)
const {projectId} = useSource()

if (!cachedFeatureRequest) {
cachedFeatureRequest = fetchFeatures({versionedClient}).pipe(
if (!cachedFeatureRequest.get(projectId)) {
const features = fetchFeatures({versionedClient}).pipe(
shareReplay(),
catchError((error) => {
console.error(error)
// Return an empty list of features if the request fails
return of([])
}),
)
cachedFeatureRequest.set(projectId, features)
}

const featureInfo = useMemoObservable(
() =>
cachedFeatureRequest.pipe(
(cachedFeatureRequest.get(projectId) || of([])).pipe(
map((features = []) => ({
isLoading: false,
enabled: Boolean(features?.includes(featureKey)),
Expand All @@ -59,7 +62,7 @@ export function useFeatureEnabled(featureKey: string): Features {
return of({isLoading: false, enabled: true, features: []})
}),
),
[featureKey],
[featureKey, projectId],
INITIAL_LOADING_STATE,
)

Expand Down

0 comments on commit 905e811

Please sign in to comment.