123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- import {useEffect, useMemo} from 'react';
- import OrganizationStore from 'sentry/stores/organizationStore';
- import TeamStore from 'sentry/stores/teamStore';
- import {useLegacyStore} from 'sentry/stores/useLegacyStore';
- import type {Team} from 'sentry/types';
- import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
- import type {ApiQueryKey} from 'sentry/utils/queryClient';
- import {useApiQuery} from 'sentry/utils/queryClient';
- interface UseTeamsResult {
- isError: boolean | null;
- isLoading: boolean;
- teams: Team[];
- }
- function buildUserTeamsQueryKey(orgSlug: string): ApiQueryKey {
- return [`/organizations/${orgSlug}/user-teams/`];
- }
- /**
- * Fetches the user's teams if they aren't already in the TeamStore.
- * @returns an array of user's teams, isLoading, and isError
- *
- * example usage:
- * ```ts
- * const {teams, isLoading, isError} = useUserTeams();
- * ```
- */
- export function useUserTeams(): UseTeamsResult {
- const {organization} = useLegacyStore(OrganizationStore);
- const storeState = useLegacyStore(TeamStore);
- // Wait until the store has loaded to start fetching
- const shouldConsiderFetching = !!organization?.slug && !storeState.loading;
- // Only fetch if there are missing teams
- const hasMissing = !storeState.loadedUserTeams;
- const queryEnabled = shouldConsiderFetching && hasMissing;
- const {
- data: additionalTeams = [],
- isLoading,
- isError,
- } = useApiQuery<Team[]>(buildUserTeamsQueryKey(organization?.slug ?? ''), {
- staleTime: 0,
- enabled: queryEnabled,
- });
- // Save fetched teams to the team store
- useEffect(() => {
- if (additionalTeams.length > 0) {
- TeamStore.loadUserTeams(additionalTeams);
- }
- }, [additionalTeams]);
- const isSuperuser = isActiveSuperuser();
- const isOrgOwner = organization?.access.includes('org:admin');
- const teams = useMemo<Team[]>(() => {
- return isSuperuser || isOrgOwner
- ? storeState.teams
- : storeState.teams.filter(t => t.isMember);
- }, [isSuperuser, isOrgOwner, storeState.teams]);
- return {
- teams,
- isLoading: queryEnabled ? isLoading : storeState.loading,
- isError: queryEnabled ? isError : null,
- };
- }
|