'use client'; import { useCallback, useMemo } from 'react'; import { useFetch } from '@gitroom/helpers/utils/custom.fetch'; import useSWR from 'swr'; import { useUser } from '@gitroom/frontend/components/layout/user.context'; export const OrganizationSelector = () => { const fetch = useFetch(); const user = useUser(); const load = useCallback(async () => { return await (await fetch('/user/organizations')).json(); }, []); const { isLoading, data } = useSWR('organizations', load, { revalidateIfStale: false, revalidateOnFocus: false, refreshWhenOffline: false, refreshWhenHidden: false, revalidateOnReconnect: false, }); const current = useMemo(() => { return data?.find((d: any) => d.id === user?.orgId); }, [data]); const withoutCurrent = useMemo(() => { return data?.filter((d: any) => d.id !== user?.orgId); }, [current, data]); const changeOrg = useCallback( (org: { name: string; id: string }) => async () => { await fetch('/user/change-org', { method: 'POST', body: JSON.stringify({ id: org.id }), }); window.location.reload(); }, [] ); if (isLoading || !isLoading && data?.length === 1) { return null; } return (
{current?.name || 'Loading...'}
{data?.length > 1 && (
)}
{data?.length > 1 && (
{withoutCurrent?.map((org: { name: string; id: string }) => (
{org.name}
))}
)}
); };