Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: move orgs and projects to react-query

Alaister Young31091d3fe492
diff --git a/studio/components/interfaces/App/CommandMenuWrapper.tsx b/studio/components/interfaces/App/CommandMenuWrapper.tsx
index c45cae8447f..b08467d59c3 100644
--- a/studio/components/interfaces/App/CommandMenuWrapper.tsx
+++ b/studio/components/interfaces/App/CommandMenuWrapper.tsx
@@ -1,25 +1,25 @@
-import remarkGfm from 'remark-gfm'
-import ReactMarkdown from 'react-markdown'
-import { PropsWithChildren, useMemo } from 'react'
-import { useParams } from 'common'
-import { CommandMenuProvider, markdownComponents } from 'ui'
-import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useParams } from 'common'
+import { PropsWithChildren, useMemo } from 'react'
+import { CommandMenuProvider } from 'ui'
-import { uuidv4 } from 'lib/helpers'
-import { checkPermissions, useFlag, useStore } from 'hooks'
-import { createSqlSnippetSkeleton } from '../SQLEditor/SQLEditor.utils'
-import { useSqlEditorStateSnapshot } from 'state/sql-editor'
import { codeBlock } from 'common-tags'
-import { SqlSnippet } from 'data/content/sql-snippets-query'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { useProjectApiQuery } from 'data/config/project-api-query'
+import { SqlSnippet } from 'data/content/sql-snippets-query'
import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
import { useProfileQuery } from 'data/profile/profile-query'
+import { checkPermissions, useFlag, useSelectedOrganization, useStore } from 'hooks'
+import { uuidv4 } from 'lib/helpers'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+import { createSqlSnippetSkeleton } from '../SQLEditor/SQLEditor.utils'
-const CommandMenuWrapper = observer(({ children }: PropsWithChildren<{}>) => {
+const CommandMenuWrapper = ({ children }: PropsWithChildren<{}>) => {
const { ref } = useParams()
const { ui } = useStore()
- const { opt_in_tags } = ui.selectedOrganization ?? {}
+ const selectedOrganization = useSelectedOrganization()
+ const { project: selectedProject } = useProjectContext()
+ const opt_in_tags = selectedOrganization?.opt_in_tags
const snap = useSqlEditorStateSnapshot()
const allowCMDKDataOptIn = useFlag('dashboardCmdkDataOptIn')
@@ -39,8 +39,8 @@ const CommandMenuWrapper = observer(({ children }: PropsWithChildren<{}>) => {
const { data } = useEntityDefinitionsQuery(
{
- projectRef: ui.selectedProject?.ref,
- connectionString: ui.selectedProject?.connectionString,
+ projectRef: selectedProject?.ref,
+ connectionString: selectedProject?.connectionString,
},
{ enabled: isOptedInToAI }
)
@@ -105,6 +105,6 @@ const CommandMenuWrapper = observer(({ children }: PropsWithChildren<{}>) => {
{children}
</CommandMenuProvider>
)
-})
+}
export default CommandMenuWrapper
diff --git a/studio/components/interfaces/App/RouteValidationWrapper.tsx b/studio/components/interfaces/App/RouteValidationWrapper.tsx
index f6ca98bf22d..201e1cd540f 100644
--- a/studio/components/interfaces/App/RouteValidationWrapper.tsx
+++ b/studio/components/interfaces/App/RouteValidationWrapper.tsx
@@ -1,15 +1,15 @@
-import { FC, useEffect } from 'react'
import { observer } from 'mobx-react-lite'
import { useRouter } from 'next/router'
+import { FC, useEffect } from 'react'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useProjectsQuery } from 'data/projects/projects-query'
import { useStore } from 'hooks'
-import { Organization, Project } from 'types'
+import useLatest from 'hooks/misc/useLatest'
// Ideally these could all be within a _middleware when we use Next 12
const RouteValidationWrapper: FC = ({ children }) => {
- const { ui, app } = useStore()
- const orgsInitialized = app.organizations.isInitialized
- const projectsInitialized = app.projects.isInitialized
+ const { ui } = useStore()
const router = useRouter()
const projectRef = router.query.ref
@@ -36,14 +36,17 @@ const RouteValidationWrapper: FC = ({ children }) => {
return excemptUrls.includes(router?.pathname)
}
+ const { data: organizations, isSuccess: orgsInitialized } = useOrganizationsQuery()
+ const organizationsRef = useLatest(organizations)
+
useEffect(() => {
// check if current route is excempted from route validation check
if (isExceptUrl()) return
if (orgsInitialized && orgSlug) {
// Check validity of organization that user is trying to access
- const organizations = app.organizations.list()
- const isValidOrg = organizations.some((org: Organization) => org.slug === orgSlug)
+ const organizations = organizationsRef.current ?? []
+ const isValidOrg = organizations.some((org) => org.slug === orgSlug)
if (!isValidOrg) {
ui.setNotification({ category: 'error', message: 'This organization does not exist' })
@@ -53,14 +56,17 @@ const RouteValidationWrapper: FC = ({ children }) => {
}
}, [orgsInitialized])
+ const { data: projects, isSuccess: projectsInitialized } = useProjectsQuery()
+ const projectsRef = useLatest(projects)
+
useEffect(() => {
// check if current route is excempted from route validation check
if (isExceptUrl()) return
if (projectsInitialized && projectRef) {
// Check validity of project that the user is trying to access
- const projects = app.projects.list()
- const isValidProject = projects.some((project: Project) => project.ref === projectRef)
+ const projects = projectsRef.current ?? []
+ const isValidProject = projects.some((project) => project.ref === projectRef)
if (!isValidProject) {
ui.setNotification({ category: 'error', message: 'This project does not exist' })
diff --git a/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx b/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx
index 673fdaebd80..43d80b3229c 100644
--- a/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx
+++ b/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx
@@ -1,16 +1,17 @@
-import { FC, useState } from 'react'
-import ReactMarkdown from 'react-markdown'
import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { FC, useState } from 'react'
+import ReactMarkdown from 'react-markdown'
import { Alert, Button, Collapsible, Form, IconCheck, IconChevronUp, Input } from 'ui'
-import { useStore, checkPermissions } from 'hooks'
+import { useParams } from 'common'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
+import { checkPermissions, useStore } from 'hooks'
import { BASE_PATH } from 'lib/constants'
-import { Provider } from './AuthProvidersForm.types'
import { ProviderCollapsibleClasses } from './AuthProvidersForm.constants'
+import { Provider } from './AuthProvidersForm.types'
import FormField from './FormField'
-import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
-import { useParams } from 'common'
interface Props {
provider: Provider
@@ -19,6 +20,7 @@ interface Props {
const ProviderForm: FC<Props> = ({ provider }) => {
const [open, setOpen] = useState(false)
const { authConfig, ui } = useStore()
+ const { project: selectedProject } = useProjectContext()
const { ref } = useParams()
const doubleNegativeKeys = ['MAILER_AUTOCONFIRM', 'SMS_AUTOCONFIRM']
const canUpdateConfig = checkPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')
@@ -160,7 +162,7 @@ const ProviderForm: FC<Props> = ({ provider }) => {
value={
customDomainData?.customDomain
? `https://${customDomainData.customDomain?.hostname}/auth/v1/callback`
- : `https://${ui.selectedProjectRef}.supabase.co/auth/v1/callback`
+ : `https://${selectedProject?.ref}.supabase.co/auth/v1/callback`
}
/>
</>
diff --git a/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddNewPaymentMethodModal.tsx b/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddNewPaymentMethodModal.tsx
index d8f6c0335f0..60d8715ba37 100644
--- a/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddNewPaymentMethodModal.tsx
+++ b/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddNewPaymentMethodModal.tsx
@@ -1,15 +1,15 @@
import HCaptcha from '@hcaptcha/react-hcaptcha'
-import { loadStripe } from '@stripe/stripe-js'
import { Elements } from '@stripe/react-stripe-js'
+import { loadStripe } from '@stripe/stripe-js'
import { FC, useCallback, useEffect, useState } from 'react'
-import { Modal } from 'ui'
-import { useStore } from 'hooks'
-import { useIsHCaptchaLoaded } from 'stores/hcaptcha-loaded-store'
+import { useTheme } from 'common'
+import { useSelectedOrganization, useStore } from 'hooks'
import { post } from 'lib/common/fetch'
import { API_URL, STRIPE_PUBLIC_KEY } from 'lib/constants'
+import { useIsHCaptchaLoaded } from 'stores/hcaptcha-loaded-store'
+import { Modal } from 'ui'
import AddPaymentMethodForm from './AddPaymentMethodForm'
-import { useTheme } from 'common'
interface Props {
visible: boolean
@@ -60,10 +60,12 @@ const AddNewPaymentMethodModal: FC<Props> = ({ visible, returnUrl, onCancel, onC
captchaRef?.resetCaptcha()
}
+ const selectedOrganization = useSelectedOrganization()
+
const setupIntent = async (hcaptchaToken: string | undefined) => {
setIntent(undefined)
- const orgSlug = ui.selectedOrganization?.slug ?? ''
+ const orgSlug = selectedOrganization?.slug ?? ''
const intent = await post(`${API_URL}/organizations/${orgSlug}/payments/setup-intent`, {
hcaptchaToken,
})
diff --git a/studio/components/interfaces/BillingV2/Subscription/AddOns/ComputeInstanceSidePanel.tsx b/studio/components/interfaces/BillingV2/Subscription/AddOns/ComputeInstanceSidePanel.tsx
index 43d224f320d..253b3c0e21e 100644
--- a/studio/components/interfaces/BillingV2/Subscription/AddOns/ComputeInstanceSidePanel.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/AddOns/ComputeInstanceSidePanel.tsx
@@ -1,15 +1,19 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQueryClient } from '@tanstack/react-query'
import clsx from 'clsx'
+import Link from 'next/link'
+import { useRouter } from 'next/router'
+import { useEffect, useState } from 'react'
+
import { useParams, useTheme } from 'common'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { invalidateProjectsQuery } from 'data/projects/projects-query'
import { useProjectAddonRemoveMutation } from 'data/subscriptions/project-addon-remove-mutation'
import { useProjectAddonUpdateMutation } from 'data/subscriptions/project-addon-update-mutation'
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'
import { checkPermissions, useStore } from 'hooks'
-import { BASE_PATH, PROJECT_STATUS } from 'lib/constants'
-import Link from 'next/link'
-import { useRouter } from 'next/router'
-import { useEffect, useState } from 'react'
+import { BASE_PATH } from 'lib/constants'
import { useSubscriptionPageStateSnapshot } from 'state/subscription-page'
import { Alert, Button, IconExternalLink, Modal, Radio, SidePanel } from 'ui'
@@ -34,10 +38,12 @@ const COMPUTE_CATEGORY_OPTIONS: {
]
const ComputeInstanceSidePanel = () => {
- const { ui, app } = useStore()
+ const queryClient = useQueryClient()
+ const { ui } = useStore()
const router = useRouter()
const { ref: projectRef } = useParams()
const { isDarkMode } = useTheme()
+ const { project: selectedProject } = useProjectContext()
const [isSubmitting, setIsSubmitting] = useState(false)
const [showConfirmationModal, setShowConfirmationModal] = useState(false)
@@ -55,7 +61,7 @@ const ComputeInstanceSidePanel = () => {
const { mutateAsync: updateAddon } = useProjectAddonUpdateMutation()
const { mutateAsync: removeAddon } = useProjectAddonRemoveMutation()
- const projectId = ui.selectedProject?.id
+ const projectId = selectedProject?.id
const selectedAddons = addons?.selected_addons ?? []
const availableAddons = addons?.available_addons ?? []
@@ -100,7 +106,7 @@ const ComputeInstanceSidePanel = () => {
category: 'success',
message: `Successfully updated compute instance to ${selectedCompute?.name}. Your project is currently being restarted to update its instance`,
})
- app.onProjectStatusUpdated(projectId, PROJECT_STATUS.RESTORING)
+ await invalidateProjectsQuery(queryClient)
onClose()
router.push(`/project/${projectRef}`)
} catch (error: any) {
diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/AddNewPaymentMethodModal.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/AddNewPaymentMethodModal.tsx
index b00322e8279..d5383ced140 100644
--- a/studio/components/interfaces/BillingV2/Subscription/Tier/AddNewPaymentMethodModal.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/AddNewPaymentMethodModal.tsx
@@ -1,15 +1,16 @@
import HCaptcha from '@hcaptcha/react-hcaptcha'
import { Elements } from '@stripe/react-stripe-js'
import { loadStripe } from '@stripe/stripe-js'
+import { useCallback, useEffect, useState } from 'react'
+
+import { useTheme } from 'common'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
-import { useStore } from 'hooks'
+import { useSelectedOrganization, useStore } from 'hooks'
import { post } from 'lib/common/fetch'
import { API_URL, STRIPE_PUBLIC_KEY } from 'lib/constants'
-import { useCallback, useEffect, useState } from 'react'
import { useIsHCaptchaLoaded } from 'stores/hcaptcha-loaded-store'
import { Modal } from 'ui'
import AddNewPaymentMethodForm from './AddNewPaymentMethodForm'
-import { useTheme } from 'common'
// [Joshen] Directly brought over from old Billing folder, so we can deprecate that folder easily next time
@@ -66,10 +67,12 @@ const AddNewPaymentMethodModal = ({
captchaRef?.resetCaptcha()
}
+ const selectedOrganization = useSelectedOrganization()
+
const setupIntent = async (hcaptchaToken: string | undefined) => {
setIntent(undefined)
- const orgSlug = ui.selectedOrganization?.slug ?? ''
+ const orgSlug = selectedOrganization?.slug ?? ''
const intent = await post(`${API_URL}/organizations/${orgSlug}/payments/setup-intent`, {
hcaptchaToken,
})
diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx
index 404045ec10d..bafd70e66d2 100644
--- a/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx
@@ -1,17 +1,19 @@
import HCaptcha from '@hcaptcha/react-hcaptcha'
-import * as Tooltip from '@radix-ui/react-tooltip'
+import { useQueryClient } from '@tanstack/react-query'
+import { includes, without } from 'lodash'
+import { useRouter } from 'next/router'
+import { useReducer, useRef, useState } from 'react'
+
import { useParams } from 'common'
+import { invalidateProjectsQuery } from 'data/projects/projects-query'
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
import { useProjectSubscriptionUpdateMutation } from 'data/subscriptions/project-subscription-update-mutation'
import { useFlag, useStore } from 'hooks'
import { post } from 'lib/common/fetch'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
-import { includes, without } from 'lodash'
-import { useRouter } from 'next/router'
-import { useReducer, useRef, useState } from 'react'
+import { API_URL } from 'lib/constants'
import { Button, Input, Modal } from 'ui'
-import ProjectUpdateDisabledTooltip from '../../ProjectUpdateDisabledTooltip'
import { CANCELLATION_REASONS } from '../../Billing.constants'
+import ProjectUpdateDisabledTooltip from '../../ProjectUpdateDisabledTooltip'
export interface ExitSurveyModalProps {
visible: boolean
@@ -21,7 +23,8 @@ export interface ExitSurveyModalProps {
// [Joshen] For context - Exit survey is only when going to free plan from a paid plan
const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {
- const { ui, app } = useStore()
+ const queryClient = useQueryClient()
+ const { ui } = useStore()
const { ref: projectRef } = useParams()
const captchaRef = useRef<HCaptcha>(null)
const router = useRouter()
@@ -35,7 +38,6 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {
const { data: addons } = useProjectAddonsQuery({ projectRef })
const { mutateAsync: updateSubscriptionTier } = useProjectSubscriptionUpdateMutation()
- const projectId = ui.selectedProject?.id ?? -1
const subscriptionAddons = addons?.selected_addons ?? []
const hasComputeInstance = subscriptionAddons.find((addon) => addon.type === 'compute_instance')
@@ -118,7 +120,7 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {
: 'Successfully downgraded project to the free plan',
})
if (hasComputeInstance) {
- app.onProjectStatusUpdated(projectId, PROJECT_STATUS.RESTORING)
+ await invalidateProjectsQuery(queryClient)
router.push(`/project/${projectRef}`)
}
onClose(true)
diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/MembersExceedLimitModal.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/MembersExceedLimitModal.tsx
index 82d3c770205..501e9259135 100644
--- a/studio/components/interfaces/BillingV2/Subscription/Tier/MembersExceedLimitModal.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/MembersExceedLimitModal.tsx
@@ -1,5 +1,5 @@
import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'
-import { useStore } from 'hooks'
+import { useSelectedOrganization } from 'hooks'
import { Button, Modal } from 'ui'
export interface MembersExceedLimitModalProps {
@@ -8,8 +8,8 @@ export interface MembersExceedLimitModalProps {
}
const MembersExceedLimitModal = ({ visible, onClose }: MembersExceedLimitModalProps) => {
- const { ui } = useStore()
- const slug = ui.selectedOrganization?.slug
+ const selectedOrganization = useSelectedOrganization()
+ const slug = selectedOrganization?.slug
const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery({ slug })
return (
diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/PaymentMethodSelection.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/PaymentMethodSelection.tsx
index 6c499a3b6c5..f0716fe15f5 100644
--- a/studio/components/interfaces/BillingV2/Subscription/Tier/PaymentMethodSelection.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/PaymentMethodSelection.tsx
@@ -1,12 +1,13 @@
import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useEffect, useMemo, useState } from 'react'
+
import { useParams } from 'common'
import { useOrganizationCustomerProfileQuery } from 'data/organizations/organization-customer-profile-query'
import { useOrganizationPaymentMethodsQuery } from 'data/organizations/organization-payment-methods-query'
-import { checkPermissions, useStore } from 'hooks'
+import { checkPermissions, useSelectedOrganization, useStore } from 'hooks'
import { BASE_PATH } from 'lib/constants'
import { getURL } from 'lib/helpers'
-import { useEffect, useMemo, useState } from 'react'
import { Button, IconAlertCircle, IconCreditCard, IconLoader, IconPlus, Listbox } from 'ui'
import AddNewPaymentMethodModal from './AddNewPaymentMethodModal'
@@ -21,7 +22,8 @@ const PaymentMethodSelection = ({
}: PaymentMethodSelectionProps) => {
const { ui } = useStore()
const { ref: projectRef } = useParams()
- const slug = ui.selectedOrganization?.slug
+ const selectedOrganization = useSelectedOrganization()
+ const slug = selectedOrganization?.slug
const [showAddNewPaymentMethodModal, setShowAddNewPaymentMethodModal] = useState(false)
const {
diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/SubscriptionPaymentMethod.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/SubscriptionPaymentMethod.tsx
index 1b1a26c910f..5d976888e09 100644
--- a/studio/components/interfaces/BillingV2/Subscription/Tier/SubscriptionPaymentMethod.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/SubscriptionPaymentMethod.tsx
@@ -1,18 +1,19 @@
-import Panel from 'components/ui/Panel'
-import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'
-import { Button, IconCreditCard, Modal } from 'ui'
import * as Tooltip from '@radix-ui/react-tooltip'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useState } from 'react'
-import PaymentMethodSelection from './PaymentMethodSelection'
+
import { useParams } from 'common'
+import Panel from 'components/ui/Panel'
import {
SubscriptionTier,
updateSubscriptionTier,
} from 'data/subscriptions/project-subscription-update-mutation'
-import { checkPermissions, useStore } from 'hooks'
+import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'
+import { checkPermissions, useSelectedOrganization, useStore } from 'hooks'
import { BASE_PATH } from 'lib/constants'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
import Link from 'next/link'
+import { Button, IconCreditCard, Modal } from 'ui'
+import PaymentMethodSelection from './PaymentMethodSelection'
export interface SubscriptionTierProps {
subscription: ProjectSubscriptionResponse
@@ -26,7 +27,8 @@ const SubscriptionPaymentMethod = ({
const { ref: projectRef } = useParams()
const { ui } = useStore()
- const currentOrgSlug = ui.selectedOrganization?.slug
+ const selectedOrganization = useSelectedOrganization()
+ const currentOrgSlug = selectedOrganization?.slug
const canUpdatePaymentMethod = checkPermissions(
PermissionAction.BILLING_WRITE,
diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/SubscriptionTier.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/SubscriptionTier.tsx
index a26e3eec82b..5a6e59c89cb 100644
--- a/studio/components/interfaces/BillingV2/Subscription/Tier/SubscriptionTier.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/SubscriptionTier.tsx
@@ -1,22 +1,23 @@
+import dayjs from 'dayjs'
+import Link from 'next/link'
+
import { useParams } from 'common'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import SparkBar from 'components/ui/SparkBar'
import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'
-import dayjs from 'dayjs'
+import { useFlag, useSelectedOrganization } from 'hooks'
import { useSubscriptionPageStateSnapshot } from 'state/subscription-page'
import { Alert, Button, IconExternalLink } from 'ui'
-import TierUpdateSidePanel from './TierUpdateSidePanel'
-import Link from 'next/link'
-import { useFlag, useStore } from 'hooks'
import ProjectUpdateDisabledTooltip from '../../ProjectUpdateDisabledTooltip'
import SubscriptionPaymentMethod from './SubscriptionPaymentMethod'
+import TierUpdateSidePanel from './TierUpdateSidePanel'
export interface SubscriptionTierProps {}
const SubscriptionTier = ({}: SubscriptionTierProps) => {
const { ref: projectRef } = useParams()
- const { ui } = useStore()
- const orgSlug = ui.selectedOrganization?.slug ?? ''
+ const selectedOrganization = useSelectedOrganization()
+ const orgSlug = selectedOrganization?.slug ?? ''
const snap = useSubscriptionPageStateSnapshot()
const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
const { data: subscription, isLoading, refetch } = useProjectSubscriptionV2Query({ projectRef })
diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/TierUpdateSidePanel.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/TierUpdateSidePanel.tsx
index d2b685bb27c..62f9a2aa6bc 100644
--- a/studio/components/interfaces/BillingV2/Subscription/Tier/TierUpdateSidePanel.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/TierUpdateSidePanel.tsx
@@ -1,28 +1,30 @@
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import clsx from 'clsx'
+import Link from 'next/link'
+import { useEffect, useState } from 'react'
+
import { useParams } from 'common'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
import { useProjectPlansQuery } from 'data/subscriptions/project-plans-query'
import { useProjectSubscriptionUpdateMutation } from 'data/subscriptions/project-subscription-update-mutation'
-import { checkPermissions, useStore } from 'hooks'
-import Link from 'next/link'
-import { useEffect, useState } from 'react'
+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'
+import { checkPermissions, useSelectedOrganization, useStore } from 'hooks'
+import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
+import { plans as subscriptionsPlans } from 'shared-data/plans'
import { useSubscriptionPageStateSnapshot } from 'state/subscription-page'
import { Alert, Button, IconCheck, IconExternalLink, Modal, SidePanel } from 'ui'
import EnterpriseCard from './EnterpriseCard'
import ExitSurveyModal from './ExitSurveyModal'
import MembersExceedLimitModal from './MembersExceedLimitModal'
import PaymentMethodSelection from './PaymentMethodSelection'
-import { plans as subscriptionsPlans } from 'shared-data/plans'
-import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'
-import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import * as Tooltip from '@radix-ui/react-tooltip'
const TierUpdateSidePanel = () => {
const { ui } = useStore()
- const slug = ui.selectedOrganization?.slug
+ const selectedOrganization = useSelectedOrganization()
+ const slug = selectedOrganization?.slug
const { ref: projectRef } = useParams()
const [isSubmitting, setIsSubmitting] = useState(false)
diff --git a/studio/components/interfaces/Database/Backups/BackupItem.tsx b/studio/components/interfaces/Database/Backups/BackupItem.tsx
index e17c909e7e6..09196074c80 100644
--- a/studio/components/interfaces/Database/Backups/BackupItem.tsx
+++ b/studio/components/interfaces/Database/Backups/BackupItem.tsx
@@ -1,14 +1,15 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
-import { FC, useState } from 'react'
import { useRouter } from 'next/router'
-import { observer } from 'mobx-react-lite'
-import { Badge, Button, IconDownload } from 'ui'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { FC, useState } from 'react'
-import { useStore, checkPermissions } from 'hooks'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
-import { post } from 'lib/common/fetch'
import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'
+import { invalidateProjectsQuery } from 'data/projects/projects-query'
+import { checkPermissions, useStore } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { Badge, Button, IconDownload } from 'ui'
interface Props {
projectRef: string
@@ -17,13 +18,13 @@ interface Props {
}
const BackupItem: FC<Props> = ({ projectRef, backup, index }) => {
+ const queryClient = useQueryClient()
const router = useRouter()
- const { app, ui } = useStore()
+ const { ui } = useStore()
const [isDownloading, setDownloading] = useState<boolean>(false)
const [isRestoring, setRestoring] = useState<boolean>(false)
- const projectId = ui.selectedProject?.id ?? -1
const canTriggerScheduledBackups = checkPermissions(
PermissionAction.INFRA_EXECUTE,
'queue_job.restore.prepare'
@@ -34,7 +35,7 @@ const BackupItem: FC<Props> = ({ projectRef, backup, index }) => {
try {
post(`${API_URL}/database/${projectRef}/backups/restore`, backup).then(() => {
setTimeout(() => {
- app.onProjectStatusUpdated(projectId, PROJECT_STATUS.RESTORING)
+ invalidateProjectsQuery(queryClient)
ui.setNotification({
category: 'success',
message: `Restoring database back to ${dayjs(backup.inserted_at).format(
@@ -132,4 +133,4 @@ const BackupItem: FC<Props> = ({ projectRef, backup, index }) => {
)
}
-export default observer(BackupItem)
+export default BackupItem
diff --git a/studio/components/interfaces/Database/Backups/BackupsList.tsx b/studio/components/interfaces/Database/Backups/BackupsList.tsx
index 59e94d83ed1..e0deec29580 100644
--- a/studio/components/interfaces/Database/Backups/BackupsList.tsx
+++ b/studio/components/interfaces/Database/Backups/BackupsList.tsx
@@ -1,23 +1,24 @@
-import { FC } from 'react'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import { observer } from 'mobx-react-lite'
+import { FC } from 'react'
-import { useStore, checkPermissions } from 'hooks'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import InformationBox from 'components/ui/InformationBox'
import Loading from 'components/ui/Loading'
-import UpgradeToPro from 'components/ui/UpgradeToPro'
import Panel from 'components/ui/Panel'
-
+import UpgradeToPro from 'components/ui/UpgradeToPro'
+import { checkPermissions, useStore } from 'hooks'
+import { IconAlertCircle, IconClock } from 'ui'
import BackupItem from './BackupItem'
-import BackupsError from './BackupsError'
import BackupsEmpty from './BackupsEmpty'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import InformationBox from 'components/ui/InformationBox'
-import { IconAlertCircle, IconClock } from 'ui'
+import BackupsError from './BackupsError'
interface Props {}
const BackupsList: FC<Props> = ({}) => {
- const { ui, backups } = useStore()
- const projectRef = ui.selectedProject?.ref || 'default'
+ const { project: selectedProject } = useProjectContext()
+ const { backups } = useStore()
+ const projectRef = selectedProject?.ref || 'default'
const canTriggerScheduledBackups = checkPermissions(
PermissionAction.INFRA_EXECUTE,
'queue_job.restore.prepare'
diff --git a/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx b/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx
index eb1ecceb2f0..ea30c520405 100644
--- a/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx
+++ b/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx
@@ -1,35 +1,37 @@
-import dayjs from 'dayjs'
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { useQueryClient } from '@tanstack/react-query'
import { format } from 'date-fns'
+import dayjs from 'dayjs'
+import { useRouter } from 'next/router'
import { useState } from 'react'
import DatePicker from 'react-datepicker'
-import { Button, Modal, IconChevronLeft, IconChevronRight, IconHelpCircle, Alert } from 'ui'
-import * as Tooltip from '@radix-ui/react-tooltip'
+import { Alert, Button, IconChevronLeft, IconChevronRight, IconHelpCircle, Modal } from 'ui'
import { useParams } from 'common'
-import { useStore } from 'hooks'
-import { post } from 'lib/common/fetch'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
import { FormHeader, FormPanel } from 'components/ui/Forms'
import InformationBox from 'components/ui/InformationBox'
-import TimeInput from './TimeInput'
-import TimezoneSelection from './TimezoneSelection'
+import { invalidateProjectsQuery } from 'data/projects/projects-query'
+import { useStore } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import BackupsEmpty from '../BackupsEmpty'
import { Timezone } from './PITR.types'
-import PITRStatus from './PITRStatus'
import {
constrainDateToRange,
formatNumberToTwoDigits,
getClientTimezone,
getDatesBetweenRange,
} from './PITR.utils'
-import { useRouter } from 'next/router'
-import BackupsEmpty from '../BackupsEmpty'
+import PITRStatus from './PITRStatus'
+import TimeInput from './TimeInput'
+import TimezoneSelection from './TimezoneSelection'
-const PITRSelection = ({}) => {
+const PITRSelection = () => {
+ const queryClient = useQueryClient()
const router = useRouter()
const { ref } = useParams()
- const { app, ui, backups } = useStore()
- const projectId = ui.selectedProject?.id ?? -1
+ const { ui, backups } = useStore()
const [selectedTimezone, setSelectedTimezone] = useState<Timezone>(getClientTimezone())
@@ -114,7 +116,7 @@ const PITRSelection = ({}) => {
} else {
setTimeout(() => {
setShowConfirmation(false)
- app.onProjectStatusUpdated(projectId, PROJECT_STATUS.RESTORING)
+ invalidateProjectsQuery(queryClient)
router.push(`/project/${projectRef}`)
}, 3000)
}
diff --git a/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx b/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
index f08cdfde803..025e271ef86 100644
--- a/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
+++ b/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
@@ -1,13 +1,14 @@
-import { FC } from 'react'
-import { useRouter } from 'next/router'
-import { includes } from 'lodash'
-import { Button, Dropdown, IconEdit3, IconFileText, IconMoreVertical, IconTrash } from 'ui'
-import { observer } from 'mobx-react-lite'
import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { includes, noop } from 'lodash'
+import { observer } from 'mobx-react-lite'
+import { useRouter } from 'next/router'
+import { FC } from 'react'
-import { checkPermissions, useStore } from 'hooks'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import Table from 'components/to-be-cleaned/Table'
+import { checkPermissions, useStore } from 'hooks'
+import { Button, Dropdown, IconEdit3, IconFileText, IconMoreVertical, IconTrash } from 'ui'
interface Props {
schema: string
@@ -19,18 +20,19 @@ interface Props {
const FunctionList: FC<Props> = ({
schema,
filterString,
- editFunction = () => {},
- deleteFunction = () => {},
+ editFunction = noop,
+ deleteFunction = noop,
}) => {
+ const { project: selectedProject } = useProjectContext()
const router = useRouter()
- const { ui, meta } = useStore()
+ const { meta } = useStore()
const functions = meta.functions.list((fn: any) => !meta.excludedSchemas.includes(fn.schema))
const filteredFunctions = functions.filter((x: any) =>
includes(x.name.toLowerCase(), filterString.toLowerCase())
)
const _functions = filteredFunctions.filter((x) => x.schema == schema)
const isApiDocumentAvailable = schema == 'public'
- const projectRef = ui.selectedProject?.ref
+ const projectRef = selectedProject?.ref
const canUpdateFunctions = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'functions')
diff --git a/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx b/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
index 4525d36feeb..6d5ad116972 100644
--- a/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
+++ b/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
@@ -1,24 +1,23 @@
-import Image from 'next/image'
-import { useState, useRef, useEffect, MutableRefObject } from 'react'
import { PostgresTable, PostgresTrigger } from '@supabase/postgres-meta'
-import { Button, SidePanel, Form, Input, Listbox, Checkbox, Radio, Badge, Modal } from 'ui'
+import Image from 'next/image'
+import { MutableRefObject, useEffect, useRef, useState } from 'react'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { tryParseJson, uuidv4 } from 'lib/helpers'
-import HTTPRequestFields from './HTTPRequestFields'
-import { isValidHttpUrl } from './Hooks.utils'
-import { AVAILABLE_WEBHOOK_TYPES, HOOK_EVENTS } from './Hooks.constants'
-import ConfirmationModal from 'components/ui/ConfirmationModal'
-import { FormSection, FormSectionLabel, FormSectionContent } from 'components/ui/Forms'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-
+import ConfirmationModal from 'components/ui/ConfirmationModal'
+import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms'
+import { useDatabaseTriggerCreateMutation } from 'data/database-triggers/database-trigger-create-mutation'
+import { useDatabaseTriggerUpdateMutation } from 'data/database-triggers/database-trigger-update-transaction-mutation'
import {
EdgeFunctionsResponse,
useEdgeFunctionsQuery,
} from 'data/edge-functions/edge-functions-query'
-import { useDatabaseTriggerCreateMutation } from 'data/database-triggers/database-trigger-create-mutation'
-import { useDatabaseTriggerUpdateMutation } from 'data/database-triggers/database-trigger-update-transaction-mutation'
+import { useStore } from 'hooks'
+import { tryParseJson, uuidv4 } from 'lib/helpers'
+import { Button, Checkbox, Form, Input, Listbox, Modal, Radio, SidePanel } from 'ui'
+import HTTPRequestFields from './HTTPRequestFields'
+import { AVAILABLE_WEBHOOK_TYPES, HOOK_EVENTS } from './Hooks.constants'
+import { isValidHttpUrl } from './Hooks.utils'
export interface EditHookPanelProps {
visible: boolean
@@ -52,7 +51,7 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =
const { mutateAsync: updateDatabaseTrigger } = useDatabaseTriggerUpdateMutation()
const tables = meta.tables.list().sort((a, b) => (a.schema > b.schema ? 0 : -1))
- const restUrl = ui.selectedProject?.restUrl
+ const restUrl = project?.restUrl
const restUrlTld = new URL(restUrl as string).hostname.split('.').pop()
const isEdgeFunction = (url: string) =>
diff --git a/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx b/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
index 0eb915a6b8a..cc4cf1919cc 100644
--- a/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
+++ b/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
@@ -1,22 +1,23 @@
+import clsx from 'clsx'
import Link from 'next/link'
+
+import { useParams } from 'common/hooks'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms'
+import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
+import { uuidv4 } from 'lib/helpers'
import {
Button,
- Listbox,
- Input,
- SidePanel,
- IconTrash,
- IconPlus,
Dropdown,
IconChevronDown,
+ IconPlus,
+ IconTrash,
+ Input,
+ Listbox,
+ SidePanel,
} from 'ui'
-import { FormSection, FormSectionLabel, FormSectionContent } from 'components/ui/Forms'
import { HTTPArgument } from './EditHookPanel'
-import { useStore } from 'hooks'
-import { useParams } from 'common/hooks'
-import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
-import clsx from 'clsx'
-import { uuidv4 } from 'lib/helpers'
-import { useProjectApiQuery } from 'data/config/project-api-query'
interface HTTPRequestFieldsProps {
type: 'http_request' | 'supabase_function'
@@ -43,7 +44,7 @@ const HTTPRequestFields = ({
onUpdateParameter,
onRemoveParameter,
}: HTTPRequestFieldsProps) => {
- const { ui } = useStore()
+ const { project: selectedProject } = useProjectContext()
const { ref } = useParams()
const { data: settings } = useProjectApiQuery({ projectRef: ref })
const { data: functions } = useEdgeFunctionsQuery({ projectRef: ref })
@@ -100,7 +101,7 @@ const HTTPRequestFields = ({
) : type === 'supabase_function' && edgeFunctions.length > 0 ? (
<Listbox id="http_url" name="http_url" label="Select which edge function to trigger">
{edgeFunctions.map((fn) => {
- const restUrl = ui.selectedProject?.restUrl
+ const restUrl = selectedProject?.restUrl
const restUrlTld = new URL(restUrl as string).hostname.split('.').pop()
const functionUrl = `https://${ref}.functions.supabase.${restUrlTld}/${fn.slug}`
diff --git a/studio/components/interfaces/Database/Hooks/HooksList/HookList.tsx b/studio/components/interfaces/Database/Hooks/HooksList/HookList.tsx
index c1754672183..b92c5d3735a 100644
--- a/studio/components/interfaces/Database/Hooks/HooksList/HookList.tsx
+++ b/studio/components/interfaces/Database/Hooks/HooksList/HookList.tsx
@@ -1,17 +1,16 @@
-import Image from 'next/image'
-import { FC } from 'react'
-import { includes } from 'lodash'
-import { observer } from 'mobx-react-lite'
import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { Badge, Button, Dropdown, IconMoreVertical, IconTrash, IconEdit3 } from 'ui'
+import { includes, noop } from 'lodash'
+import Image from 'next/image'
+import { FC } from 'react'
-import { checkPermissions, useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { BASE_PATH } from 'lib/constants'
-import Table from 'components/to-be-cleaned/Table'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import Table from 'components/to-be-cleaned/Table'
import { useDatabaseHooks } from 'data/database-triggers/database-triggers-query'
+import { checkPermissions } from 'hooks'
+import { BASE_PATH } from 'lib/constants'
+import { Badge, Button, Dropdown, IconEdit3, IconMoreVertical, IconTrash } from 'ui'
interface Props {
schema: string
@@ -20,13 +19,7 @@ interface Props {
deleteHook: (hook: any) => void
}
-const HookList: FC<Props> = ({
- schema,
- filterString,
- editHook = () => {},
- deleteHook = () => {},
-}) => {
- const { ui } = useStore()
+const HookList: FC<Props> = ({ schema, filterString, editHook = noop, deleteHook = noop }) => {
const { ref } = useParams()
const { project } = useProjectContext()
const { data: hooks } = useDatabaseHooks({
@@ -34,7 +27,7 @@ const HookList: FC<Props> = ({
connectionString: project?.connectionString,
})
- const restUrl = ui.selectedProject?.restUrl
+ const restUrl = project?.restUrl
const restUrlTld = new URL(restUrl as string).hostname.split('.').pop()
const filteredHooks = (hooks ?? []).filter(
@@ -137,4 +130,4 @@ const HookList: FC<Props> = ({
)
}
-export default observer(HookList)
+export default HookList
diff --git a/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx b/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx
index cea9b1e2fb2..4237781074c 100644
--- a/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx
+++ b/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx
@@ -1,14 +1,13 @@
+import * as Tooltip from '@radix-ui/react-tooltip'
import dayjs from 'dayjs'
-import { FC, useState } from 'react'
import { useRouter } from 'next/router'
-import { observer } from 'mobx-react-lite'
-import { IconCheck, IconClipboard } from 'ui'
-import * as Tooltip from '@radix-ui/react-tooltip'
+import { FC, useState } from 'react'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import Table from 'components/to-be-cleaned/Table'
import { EdgeFunctionsResponse } from 'data/edge-functions/edge-functions-query'
+import { IconCheck, IconClipboard } from 'ui'
interface Props {
function: EdgeFunctionsResponse
@@ -16,12 +15,12 @@ interface Props {
const EdgeFunctionsListItem: FC<Props> = ({ function: item }) => {
const router = useRouter()
- const { ui } = useStore()
const { ref } = useParams()
const [isCopied, setIsCopied] = useState(false)
+ const { project } = useProjectContext()
// get the .co or .net TLD from the restUrl
- const restUrl = ui.selectedProject?.restUrl
+ const restUrl = project?.restUrl
const restUrlTld = new URL(restUrl as string).hostname.split('.').pop()
const functionUrl = `https://${ref}.supabase.${restUrlTld}/functions/v1/${item.slug}`
@@ -103,4 +102,4 @@ const EdgeFunctionsListItem: FC<Props> = ({ function: item }) => {
)
}
-export default observer(EdgeFunctionsListItem)
+export default EdgeFunctionsListItem
diff --git a/studio/components/interfaces/Home/ProjectList/ProjectList.tsx b/studio/components/interfaces/Home/ProjectList/ProjectList.tsx
index 4f26eeb077b..0b040a4c051 100644
--- a/studio/components/interfaces/Home/ProjectList/ProjectList.tsx
+++ b/studio/components/interfaces/Home/ProjectList/ProjectList.tsx
@@ -1,25 +1,28 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { groupBy } from 'lodash'
+import { observer } from 'mobx-react-lite'
import Link from 'next/link'
-import { FC } from 'react'
import { Badge, Button, IconPlus } from 'ui'
-import { observer } from 'mobx-react-lite'
-import { IS_PLATFORM } from 'lib/constants'
+import { useOverdueInvoicesQuery } from 'data/invoices/invoices-overdue-query'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useProjectsQuery } from 'data/projects/projects-query'
import { checkPermissions, useStore } from 'hooks'
-import { Organization, Project } from 'types'
+import { IS_PLATFORM } from 'lib/constants'
import { makeRandomString } from 'lib/helpers'
import ProjectCard from './ProjectCard'
import ShimmeringCard from './ShimmeringCard'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useOverdueInvoicesQuery } from 'data/invoices/invoices-overdue-query'
-interface Props {
+export interface ProjectListProps {
rewriteHref?: (projectRef: string) => string
}
-const ProjectList: FC<Props> = ({ rewriteHref }) => {
- const { app, ui } = useStore()
- const { organizations, projects } = app
- const { isLoading: isLoadingProjects } = projects
+const ProjectList = ({ rewriteHref }: ProjectListProps) => {
+ const { ui } = useStore()
+ const { data: organizations } = useOrganizationsQuery()
+ const { data: allProjects, isLoading: isLoadingProjects } = useProjectsQuery()
+
+ const projectsByOrg = groupBy(allProjects, 'organization_id')
const { data: allOverdueInvoices } = useOverdueInvoicesQuery({ enabled: IS_PLATFORM })
@@ -27,12 +30,11 @@ const ProjectList: FC<Props> = ({ rewriteHref }) => {
return (
<>
- {organizations.list().map((org: Organization) => {
+ {organizations?.map((org) => {
const { id, name, slug, subscription_id } = org
- const sortedProjects = projects.list(
- ({ organization_id }: Project) => organization_id == id
- )
- const isEmpty = sortedProjects?.length == 0
+ const projects = projectsByOrg[id]
+
+ const isEmpty = !projects || projects.length === 0
const canReadProjects = checkPermissions(PermissionAction.READ, 'projects', undefined, id)
const overdueInvoices = (allOverdueInvoices || []).filter((it) => it.organization_id === id)
@@ -40,7 +42,10 @@ const ProjectList: FC<Props> = ({ rewriteHref }) => {
return (
<div className="space-y-3" key={makeRandomString(5)}>
<div className="flex space-x-4 items-center">
- <h4 className="text-lg flex items-center">{name}{subscription_id ? <Badge className='ml-3'>V2</Badge> : <></>}</h4>
+ <h4 className="text-lg flex items-center">
+ {name}
+ {subscription_id ? <Badge className="ml-3">V2</Badge> : <></>}
+ </h4>
{!!overdueInvoices.length && (
<div>
@@ -65,7 +70,7 @@ const ProjectList: FC<Props> = ({ rewriteHref }) => {
<div className="space-y-1">
<p>You need additional permissions to view projects from this organization</p>
<p className="text-sm text-scale-1100">
- Contact your organization owner or adminstrator for assistance.
+ Contact your organization owner or administrator for assistance.
</p>
</div>
</div>
@@ -86,7 +91,7 @@ const ProjectList: FC<Props> = ({ rewriteHref }) => {
</div>
</div>
) : (
- sortedProjects?.map((project: Project) => (
+ projects?.map((project) => (
<ProjectCard
key={makeRandomString(5)}
project={project}
diff --git a/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx b/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx
index 010510676a2..5cd45f4d518 100644
--- a/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx
+++ b/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx
@@ -1,25 +1,26 @@
-import { FC, useState } from 'react'
-import { isEqual } from 'lodash'
-import { Dictionary } from 'components/grid'
-import { Form, Input, Button, Listbox } from 'ui'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { Dictionary } from 'components/grid'
+import { isEqual } from 'lodash'
+import { useState } from 'react'
+import { Button, Form, Input, Listbox } from 'ui'
-import { checkPermissions, useStore } from 'hooks'
+import NoPermission from 'components/ui/NoPermission'
+import Panel from 'components/ui/Panel'
+import { checkPermissions, useSelectedOrganization, useStore } from 'hooks'
import { patch } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import { COUNTRIES } from './BillingAddress.constants'
-import Panel from 'components/ui/Panel'
-import NoPermission from 'components/ui/NoPermission'
-interface Props {
+export interface BillingAddressProps {
loading: boolean
address: Dictionary<any>
onAddressUpdated: (address: any) => void
}
-const BillingAddress: FC<Props> = ({ loading, address, onAddressUpdated }) => {
+const BillingAddress = ({ loading, address, onAddressUpdated }: BillingAddressProps) => {
const { ui } = useStore()
- const orgSlug = ui.selectedOrganization?.slug ?? ''
+ const selectedOrganization = useSelectedOrganization()
+ const orgSlug = selectedOrganization?.slug ?? ''
const { city, country, line1, line2, postal_code, state } = address
const canReadBillingAddress = checkPermissions(PermissionAction.BILLING_READ, 'stripe.customer')
diff --git a/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx b/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx
index b5279fd1753..7fa6c9c14b0 100644
--- a/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx
+++ b/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx
@@ -1,16 +1,21 @@
-import { useEffect } from 'react'
-import { Form, Input } from 'ui'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useStore, checkPermissions } from 'hooks'
+import { useQueryClient } from '@tanstack/react-query'
+import { useEffect } from 'react'
+
import { useParams } from 'common/hooks'
-import { API_URL } from 'lib/constants'
-import { patch } from 'lib/common/fetch'
import { FormActions, FormPanel, FormSection, FormSectionContent } from 'components/ui/Forms'
+import { invalidateOrganizationsQuery } from 'data/organizations/organizations-query'
+import { checkPermissions, useSelectedOrganization, useStore } from 'hooks'
+import { patch } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { Form, Input } from 'ui'
const BillingEmail = () => {
- const { app, ui } = useStore()
+ const queryClient = useQueryClient()
+ const { ui } = useStore()
const { slug } = useParams()
- const { name, billing_email } = ui.selectedOrganization ?? {}
+ const selectedOrganization = useSelectedOrganization()
+ const { name, billing_email } = selectedOrganization ?? {}
const formId = 'org-billing-email'
const initialValues = {
@@ -45,7 +50,7 @@ const BillingEmail = () => {
initialValues: { billing_email },
})
- app.onOrgUpdated(response)
+ invalidateOrganizationsQuery(queryClient)
ui.setNotification({
category: 'success',
message: 'Successfully saved settings',
diff --git a/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx b/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx
index 0e700116ef2..2bb878fd30c 100644
--- a/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx
+++ b/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx
@@ -1,25 +1,25 @@
-import { useState, useEffect } from 'react'
-import { observer } from 'mobx-react-lite'
+import { useEffect, useState } from 'react'
-import { Project } from 'types'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { API_URL } from 'lib/constants'
+import { useProjectsQuery } from 'data/projects/projects-query'
+import { useSelectedOrganization, useStore } from 'hooks'
import { get } from 'lib/common/fetch'
-
-import ProjectsSummary from './ProjectsSummary'
+import { API_URL } from 'lib/constants'
+import BillingAddress from './BillingAddress/BillingAddress'
+import BillingEmail from './BillingEmail'
import CreditBalance from './CreditBalance'
import PaymentMethods from './PaymentMethods'
-import BillingAddress from './BillingAddress/BillingAddress'
+import ProjectsSummary from './ProjectsSummary'
import TaxID from './TaxID/TaxID'
-import BillingEmail from './BillingEmail'
const BillingSettings = () => {
- const { app, ui } = useStore()
+ const { ui } = useStore()
const { slug } = useParams()
- const organization = ui.selectedOrganization
- const projects = app.projects.list((x: Project) => x.organization_id == organization?.id) || []
+ const organization = useSelectedOrganization()
+ const { data: allProjects } = useProjectsQuery()
+ const projects =
+ allProjects?.filter((project) => project.organization_id == organization?.id) ?? []
const [customer, setCustomer] = useState<any>(null)
const [isLoadingCustomer, setIsLoadingCustomer] = useState(false)
@@ -39,12 +39,6 @@ const BillingSettings = () => {
? customerBalance.toString().replace('-', '')
: customerBalance
- useEffect(() => {
- getCustomerProfile()
- getPaymentMethods()
- getTaxIds()
- }, [slug])
-
const getCustomerProfile = async () => {
try {
setIsLoadingCustomer(true)
@@ -93,6 +87,12 @@ const BillingSettings = () => {
}
}
+ useEffect(() => {
+ getCustomerProfile()
+ getPaymentMethods()
+ getTaxIds()
+ }, [slug])
+
return (
<article className="container my-4 max-w-4xl space-y-8">
<div className="space-y-8">
@@ -124,4 +124,4 @@ const BillingSettings = () => {
)
}
-export default observer(BillingSettings)
+export default BillingSettings
diff --git a/studio/components/interfaces/Organization/BillingSettings/PaymentMethods.tsx b/studio/components/interfaces/Organization/BillingSettings/PaymentMethods.tsx
index c77d8b7fa7f..d74754969c9 100644
--- a/studio/components/interfaces/Organization/BillingSettings/PaymentMethods.tsx
+++ b/studio/components/interfaces/Organization/BillingSettings/PaymentMethods.tsx
@@ -1,28 +1,28 @@
-import { FC, useState } from 'react'
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useState } from 'react'
import {
+ Alert,
+ Badge,
+ Button,
Dropdown,
- IconPlus,
IconCreditCard,
- Button,
- Input,
- Badge,
- Modal,
- Alert,
IconMoreHorizontal,
+ IconPlus,
IconX,
+ Input,
+ Modal,
} from 'ui'
-import * as Tooltip from '@radix-ui/react-tooltip'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { checkPermissions, useStore } from 'hooks'
-import { delete_, patch } from 'lib/common/fetch'
-import { getURL } from 'lib/helpers'
-import { API_URL, BASE_PATH } from 'lib/constants'
-import Panel from 'components/ui/Panel'
import { AddNewPaymentMethodModal } from 'components/interfaces/Billing'
import NoPermission from 'components/ui/NoPermission'
+import Panel from 'components/ui/Panel'
+import { checkPermissions, useSelectedOrganization, useStore } from 'hooks'
+import { delete_, patch } from 'lib/common/fetch'
+import { API_URL, BASE_PATH } from 'lib/constants'
+import { getURL } from 'lib/helpers'
-interface Props {
+export interface PaymentMethodsProps {
loading: boolean
defaultPaymentMethod: string
paymentMethods: any[]
@@ -31,16 +31,17 @@ interface Props {
onPaymentMethodAdded: () => void
}
-const PaymentMethods: FC<Props> = ({
+const PaymentMethods = ({
loading,
defaultPaymentMethod,
paymentMethods,
onDefaultMethodUpdated,
onPaymentMethodsDeleted,
onPaymentMethodAdded,
-}) => {
+}: PaymentMethodsProps) => {
const { ui } = useStore()
- const orgSlug = ui.selectedOrganization?.slug ?? ''
+ const selectedOrganization = useSelectedOrganization()
+ const orgSlug = selectedOrganization?.slug ?? ''
const [selectedMethodForDefault, setSelectedMethodForDefault] = useState<any>()
const [selectedMethodToDelete, setSelectedMethodToDelete] = useState<any>()
diff --git a/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.tsx b/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.tsx
index 02a33a6333e..0a7dc257ebd 100644
--- a/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.tsx
+++ b/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.tsx
@@ -1,18 +1,18 @@
-import { FC, useEffect, useState } from 'react'
-import { isEqual } from 'lodash'
-import { Input, Button, IconPlus, IconX, Listbox } from 'ui'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { isEqual } from 'lodash'
+import { useEffect, useState } from 'react'
+import { Button, IconPlus, IconX, Input, Listbox } from 'ui'
-import { checkPermissions, useFlag, useStore } from 'hooks'
-import { uuidv4 } from 'lib/helpers'
-import { post, delete_ } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
+import NoPermission from 'components/ui/NoPermission'
import Panel from 'components/ui/Panel'
+import { checkPermissions, useSelectedOrganization, useStore } from 'hooks'
+import { delete_, post } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { uuidv4 } from 'lib/helpers'
import { StripeTaxId, TAX_IDS } from './TaxID.constants'
-import NoPermission from 'components/ui/NoPermission'
import { sanitizeTaxID } from './TaxID.utils'
-interface Props {
+export interface TaxIDProps {
loading: boolean
taxIds: any[]
onTaxIdsUpdated: (taxIds: any) => void
@@ -21,9 +21,10 @@ interface Props {
// Stripe recommends to delete tax ids and create new ones to update
// https://stripe.com/docs/billing/customer/tax-ids
-const TaxID: FC<Props> = ({ loading, taxIds, onTaxIdsUpdated }) => {
+const TaxID = ({ loading, taxIds, onTaxIdsUpdated }: TaxIDProps) => {
const { ui } = useStore()
- const slug = ui.selectedOrganization?.slug ?? ''
+ const selectedOrganization = useSelectedOrganization()
+ const slug = selectedOrganization?.slug ?? ''
const [isSaving, setIsSaving] = useState(false)
const [errors, setErrors] = useState<string[]>([])
diff --git a/studio/components/interfaces/Organization/GeneralSettings/DeleteOrganizationButton.tsx b/studio/components/interfaces/Organization/GeneralSettings/DeleteOrganizationButton.tsx
index c166fad4e7e..0f101f4871f 100644
--- a/studio/components/interfaces/Organization/GeneralSettings/DeleteOrganizationButton.tsx
+++ b/studio/components/interfaces/Organization/GeneralSettings/DeleteOrganizationButton.tsx
@@ -1,18 +1,21 @@
-import { useState, useContext } from 'react'
-import { useRouter } from 'next/router'
-import { observer } from 'mobx-react-lite'
-import { Button, Form, Modal, Input } from 'ui'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQueryClient } from '@tanstack/react-query'
+import { useRouter } from 'next/router'
+import { useState } from 'react'
+import { Button, Form, Input, Modal } from 'ui'
-import { useStore, checkPermissions } from 'hooks'
+import { invalidateOrganizationsQuery } from 'data/organizations/organizations-query'
+import { checkPermissions, useSelectedOrganization, useStore } from 'hooks'
import { delete_ } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
-const DeleteOrganizationButton = observer(() => {
+const DeleteOrganizationButton = () => {
const router = useRouter()
- const { app, ui } = useStore()
+ const queryClient = useQueryClient()
+ const { ui } = useStore()
- const { slug: orgSlug, name: orgName } = ui.selectedOrganization || {}
+ const selectedOrganization = useSelectedOrganization()
+ const { slug: orgSlug, name: orgName } = selectedOrganization ?? {}
const [isOpen, setIsOpen] = useState(false)
const [value, setValue] = useState('')
@@ -47,7 +50,7 @@ const DeleteOrganizationButton = observer(() => {
})
setSubmitting(false)
} else {
- app.onOrgDeleted(ui.selectedOrganization)
+ invalidateOrganizationsQuery(queryClient)
setSubmitting(false)
router.push('/')
ui.setNotification({
@@ -119,6 +122,6 @@ const DeleteOrganizationButton = observer(() => {
</Modal>
</>
)
-})
+}
export default DeleteOrganizationButton
diff --git a/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx b/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
index 6849fe6a8b8..1cd1f294b58 100644
--- a/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
+++ b/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
@@ -1,16 +1,12 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQueryClient } from '@tanstack/react-query'
import clsx from 'clsx'
+import { observer } from 'mobx-react-lite'
import Link from 'next/link'
import { useEffect, useState } from 'react'
-import { observer } from 'mobx-react-lite'
-import { Collapsible, Form, IconChevronRight, IconHelpCircle, Input, Toggle } from 'ui'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { Collapsible, Form, IconChevronRight, Input, Toggle } from 'ui'
-import { useStore, checkPermissions, useFlag } from 'hooks'
import { useParams } from 'common/hooks'
-import { API_URL } from 'lib/constants'
-import { patch } from 'lib/common/fetch'
-
-import OrganizationDeletePanel from './OrganizationDeletePanel'
import {
FormActions,
FormPanel,
@@ -18,12 +14,19 @@ import {
FormSectionContent,
FormSectionLabel,
} from 'components/ui/Forms'
+import { invalidateOrganizationsQuery } from 'data/organizations/organizations-query'
+import { checkPermissions, useFlag, useSelectedOrganization, useStore } from 'hooks'
+import { patch } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import OrganizationDeletePanel from './OrganizationDeletePanel'
const GeneralSettings = () => {
- const { app, ui } = useStore()
+ const queryClient = useQueryClient()
+ const { ui } = useStore()
const { slug } = useParams()
const [open, setOpen] = useState(false)
- const { name, opt_in_tags } = ui.selectedOrganization ?? {}
+ const selectedOrganization = useSelectedOrganization()
+ const { name, opt_in_tags } = selectedOrganization ?? {}
const formId = 'org-general-settings'
const isOptedIntoAi = opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN')
@@ -49,7 +52,7 @@ const GeneralSettings = () => {
const optInTags = values.isOptedIntoAi ? ['AI_SQL_GENERATOR_OPT_IN'] : []
const response = await patch(`${API_URL}/organizations/${slug}`, {
name: values.name,
- billing_email: ui.selectedOrganization?.billing_email ?? '',
+ billing_email: selectedOrganization?.billing_email ?? '',
...(allowCMDKDataOptIn && { opt_in_tags: optInTags }),
})
@@ -60,7 +63,7 @@ const GeneralSettings = () => {
})
} else {
resetForm({ values, initialValues: values })
- app.onOrgUpdated(response)
+ invalidateOrganizationsQuery(queryClient)
ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
}
setSubmitting(false)
@@ -78,7 +81,7 @@ const GeneralSettings = () => {
useEffect(() => {
const values = { name: name ?? '', isOptedIntoAi }
resetForm({ values, initialValues: values })
- }, [ui.selectedOrganization?.slug])
+ }, [selectedOrganization?.slug])
return (
<FormPanel
diff --git a/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSettings.tsx b/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSettings.tsx
index aa7cb272fa9..1f7aa81e5ef 100644
--- a/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSettings.tsx
+++ b/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSettings.tsx
@@ -1,15 +1,15 @@
-import { useState, useEffect } from 'react'
-import { Button, Loading, IconFileText, IconDownload, IconChevronLeft, IconChevronRight } from 'ui'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import Link from 'next/link'
+import { useEffect, useState } from 'react'
-import { checkPermissions, useStore } from 'hooks'
-import { API_URL } from 'lib/constants'
-import { get, head } from 'lib/common/fetch'
-import Table from 'components/to-be-cleaned/Table'
-import NoPermission from 'components/ui/NoPermission'
import InvoiceStatusBadge from 'components/interfaces/Billing/InvoiceStatusBadge'
import { Invoice, InvoiceStatus } from 'components/interfaces/Billing/Invoices.types'
+import Table from 'components/to-be-cleaned/Table'
+import NoPermission from 'components/ui/NoPermission'
+import { checkPermissions, useSelectedOrganization, useStore } from 'hooks'
+import { get, head } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { Button, IconChevronLeft, IconChevronRight, IconDownload, IconFileText, Loading } from 'ui'
const PAGE_LIMIT = 10
@@ -23,7 +23,8 @@ const InvoicesSettings = () => {
const [count, setCount] = useState(0)
const [invoices, setInvoices] = useState<Invoice[]>([])
- const { stripe_customer_id } = ui.selectedOrganization ?? {}
+ const selectedOrganization = useSelectedOrganization()
+ const { stripe_customer_id } = selectedOrganization ?? {}
const offset = (page - 1) * PAGE_LIMIT
const canReadInvoices = checkPermissions(PermissionAction.READ, 'invoices')
diff --git a/studio/components/interfaces/Organization/NewProject/EmptyPaymentMethodWarning.tsx b/studio/components/interfaces/Organization/NewProject/EmptyPaymentMethodWarning.tsx
index 7a94402fe18..74ae3d7735f 100644
--- a/studio/components/interfaces/Organization/NewProject/EmptyPaymentMethodWarning.tsx
+++ b/studio/components/interfaces/Organization/NewProject/EmptyPaymentMethodWarning.tsx
@@ -1,53 +1,53 @@
import { useState } from 'react'
-import { observer } from 'mobx-react-lite'
-import { Button, IconAlertCircle } from 'ui'
-import { useStore } from 'hooks'
-import { getURL } from 'lib/helpers'
-import InformationBox from 'components/ui/InformationBox'
import { AddNewPaymentMethodModal } from 'components/interfaces/Billing'
+import InformationBox from 'components/ui/InformationBox'
+import { useSelectedOrganization } from 'hooks'
+import { getURL } from 'lib/helpers'
+import { Button, IconAlertCircle } from 'ui'
-const EmptyPaymentMethodWarning = observer(
- ({ onPaymentMethodAdded }: { onPaymentMethodAdded: () => void }) => {
- const { ui } = useStore()
- const slug = ui.selectedOrganization?.slug
-
- const [showAddPaymentMethodModal, setShowAddPaymentMethodModal] = useState<boolean>(false)
+const EmptyPaymentMethodWarning = ({
+ onPaymentMethodAdded,
+}: {
+ onPaymentMethodAdded: () => void
+}) => {
+ const selectedOrganization = useSelectedOrganization()
+ const slug = selectedOrganization?.slug
- const onLocalPaymentMethodAdded = () => {
- setShowAddPaymentMethodModal(false)
+ const [showAddPaymentMethodModal, setShowAddPaymentMethodModal] = useState<boolean>(false)
- return onPaymentMethodAdded()
- }
+ const onLocalPaymentMethodAdded = () => {
+ setShowAddPaymentMethodModal(false)
- return (
- <div className="mt-4">
- <InformationBox
- icon={<IconAlertCircle size="large" strokeWidth={1.5} />}
- defaultVisibility={true}
- hideCollapse
- title="Your organization has no payment methods"
- description={
- <div className="space-y-3">
- <p className="text-sm leading-normal">
- You need to add a payment method for your organization before creating a paid
- project.
- </p>
- <Button type="secondary" onClick={() => setShowAddPaymentMethodModal(true)}>
- Add a payment method
- </Button>
- </div>
- }
- />
- <AddNewPaymentMethodModal
- visible={showAddPaymentMethodModal}
- returnUrl={`${getURL()}/new/${slug}`}
- onCancel={() => setShowAddPaymentMethodModal(false)}
- onConfirm={() => onLocalPaymentMethodAdded()}
- />
- </div>
- )
+ return onPaymentMethodAdded()
}
-)
+
+ return (
+ <div className="mt-4">
+ <InformationBox
+ icon={<IconAlertCircle size="large" strokeWidth={1.5} />}
+ defaultVisibility={true}
+ hideCollapse
+ title="Your organization has no payment methods"
+ description={
+ <div className="space-y-3">
+ <p className="text-sm leading-normal">
+ You need to add a payment method for your organization before creating a paid project.
+ </p>
+ <Button type="secondary" onClick={() => setShowAddPaymentMethodModal(true)}>
+ Add a payment method
+ </Button>
+ </div>
+ }
+ />
+ <AddNewPaymentMethodModal
+ visible={showAddPaymentMethodModal}
+ returnUrl={`${getURL()}/new/${slug}`}
+ onCancel={() => setShowAddPaymentMethodModal(false)}
+ onConfirm={() => onLocalPaymentMethodAdded()}
+ />
+ </div>
+ )
+}
export default EmptyPaymentMethodWarning
diff --git a/studio/components/interfaces/Organization/NewProject/NotOrganizationOwnerWarning.tsx b/studio/components/interfaces/Organization/NewProject/NotOrganizationOwnerWarning.tsx
index a80724fb25c..61bc8a39cff 100644
--- a/studio/components/interfaces/Organization/NewProject/NotOrganizationOwnerWarning.tsx
+++ b/studio/components/interfaces/Organization/NewProject/NotOrganizationOwnerWarning.tsx
@@ -13,7 +13,7 @@ const NotOrganizationOwnerWarning = () => {
description={
<div className="space-y-3">
<p className="text-sm leading-normal">
- Contact your organization owner or adminstrator to create a new project.
+ Contact your organization owner or administrator to create a new project.
</p>
</div>
}
diff --git a/studio/components/interfaces/Organization/TeamSettings/TeamSettings.tsx b/studio/components/interfaces/Organization/TeamSettings/TeamSettings.tsx
index 7752b2f122f..fcb76dfc531 100644
--- a/studio/components/interfaces/Organization/TeamSettings/TeamSettings.tsx
+++ b/studio/components/interfaces/Organization/TeamSettings/TeamSettings.tsx
@@ -1,26 +1,26 @@
-import { useState } from 'react'
-import { observer } from 'mobx-react-lite'
-import { Button, Input, IconSearch } from 'ui'
import * as Tooltip from '@radix-ui/react-tooltip'
+import { useState } from 'react'
+import { Button, IconSearch, Input } from 'ui'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
+import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'
+import { useOrganizationDetailQuery } from 'data/organizations/organization-detail-query'
+import { useOrganizationRolesQuery } from 'data/organizations/organization-roles-query'
+import { useProfileQuery } from 'data/profile/profile-query'
+import { useSelectedOrganization, useStore } from 'hooks'
import { delete_ } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import InviteMemberButton from './InviteMemberButton'
import MembersView from './MembersView'
import { getRolesManagementPermissions, hasMultipleOwners } from './TeamSettings.utils'
-import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'
-import { useOrganizationDetailQuery } from 'data/organizations/organization-detail-query'
-import { useOrganizationRolesQuery } from 'data/organizations/organization-roles-query'
-import { useProfileQuery } from 'data/profile/profile-query'
const TeamSettings = () => {
const { ui } = useStore()
const { slug } = useParams()
const { data: profile } = useProfileQuery()
- const isOwner = ui.selectedOrganization?.is_owner
+ const selectedOrganization = useSelectedOrganization()
+ const isOwner = selectedOrganization?.is_owner
const { data: detailData } = useOrganizationDetailQuery({ slug })
const { data: rolesData } = useOrganizationRolesQuery({ slug })
@@ -128,4 +128,4 @@ const TeamSettings = () => {
)
}
-export default observer(TeamSettings)
+export default TeamSettings
diff --git a/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx b/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx
index b9d6b89725c..abc87975cdc 100644
--- a/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx
+++ b/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx
@@ -1,24 +1,24 @@
-import { FC, useState, useEffect, Fragment } from 'react'
-import { observer } from 'mobx-react-lite'
-import { checkPermissions, useStore } from 'hooks'
-import { pluckObjectFields } from 'lib/helpers'
-import Loading from 'components/ui/Loading'
-import Panel from 'components/ui/Panel'
-import Divider from 'components/ui/Divider'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { FC, Fragment, useEffect, useState } from 'react'
import { AutoField } from 'uniforms-bootstrap4'
-import { API_URL } from 'lib/constants'
-import { patch } from 'lib/common/fetch'
-import ToggleField from 'components/to-be-cleaned/forms/ToggleField'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import SchemaFormPanel from 'components/to-be-cleaned/forms/SchemaFormPanel'
-import { Input } from 'ui'
+import Divider from 'components/ui/Divider'
+import Panel from 'components/ui/Panel'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { checkPermissions, useStore } from 'hooks'
+import { patch } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { pluckObjectFields } from 'lib/helpers'
+import { Input } from 'ui'
interface Props {}
const ConnectionPooling: FC<Props> = () => {
- const { ui, app } = useStore()
- const projectRef = ui.selectedProject?.ref ?? 'default'
+ const { app } = useStore()
+ const { project } = useProjectContext()
+ const projectRef = project?.ref ?? 'default'
const [isLoading, setIsLoading] = useState<boolean>(true)
const [poolingConfiguration, setPoolingConfiguration] = useState<any>()
@@ -103,7 +103,7 @@ const ConnectionPooling: FC<Props> = () => {
)
}
-export default observer(ConnectionPooling)
+export default ConnectionPooling
interface ConfigProps {
projectRef: string
@@ -122,139 +122,137 @@ interface ConfigProps {
}
}
-export const PgbouncerConfig: FC<ConfigProps> = observer(
- ({ projectRef, bouncerInfo, connectionInfo }) => {
- const { ui } = useStore()
+export const PgbouncerConfig: FC<ConfigProps> = ({ projectRef, bouncerInfo, connectionInfo }) => {
+ const { ui } = useStore()
- const canUpdateConnectionPoolingConfiguration = checkPermissions(
- PermissionAction.UPDATE,
- 'projects'
- )
+ const canUpdateConnectionPoolingConfiguration = checkPermissions(
+ PermissionAction.UPDATE,
+ 'projects'
+ )
- const [updates, setUpdates] = useState<any>({
- pool_mode: bouncerInfo.pool_mode || 'transaction',
- default_pool_size: bouncerInfo.default_pool_size || '',
- ignore_startup_parameters: bouncerInfo.ignore_startup_parameters || '',
- pgbouncer_enabled: bouncerInfo.pgbouncer_enabled,
- })
+ const [updates, setUpdates] = useState<any>({
+ pool_mode: bouncerInfo.pool_mode || 'transaction',
+ default_pool_size: bouncerInfo.default_pool_size || '',
+ ignore_startup_parameters: bouncerInfo.ignore_startup_parameters || '',
+ pgbouncer_enabled: bouncerInfo.pgbouncer_enabled,
+ })
- const updateConfig = async (updatedConfig: any) => {
- try {
- const response = await patch(`${API_URL}/projects/${projectRef}/config/pgbouncer`, {
- pgbouncer_enabled: updatedConfig.pgbouncer_enabled,
- default_pool_size: updatedConfig.default_pool_size,
- ignore_startup_parameters: updatedConfig.ignore_startup_parameters,
- pool_mode: updatedConfig.pool_mode,
- max_client_conn: updatedConfig.max_client_conn,
- })
- if (response.error) {
- throw response.error
- } else {
- setUpdates({ ...response })
- ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
- }
- } catch (error: any) {
- ui.setNotification({
- category: 'error',
- message: `Failed to update config: ${error.message}`,
- })
+ const updateConfig = async (updatedConfig: any) => {
+ try {
+ const response = await patch(`${API_URL}/projects/${projectRef}/config/pgbouncer`, {
+ pgbouncer_enabled: updatedConfig.pgbouncer_enabled,
+ default_pool_size: updatedConfig.default_pool_size,
+ ignore_startup_parameters: updatedConfig.ignore_startup_parameters,
+ pool_mode: updatedConfig.pool_mode,
+ max_client_conn: updatedConfig.max_client_conn,
+ })
+ if (response.error) {
+ throw response.error
+ } else {
+ setUpdates({ ...response })
+ ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
}
+ } catch (error: any) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to update config: ${error.message}`,
+ })
}
+ }
- const formSchema = {
- properties: {
- pool_mode: {
- title: 'Pool Mode',
- type: 'string',
- options: [
- {
- label: 'Transaction',
- value: 'transaction',
- },
- {
- label: 'Session',
- value: 'session',
- },
- ],
- },
- ignore_startup_parameters: {
- title: 'Ignore Startup Parameters',
- type: 'string',
- help: 'Defaults are either blank or "extra_float_digits"',
- },
+ const formSchema = {
+ properties: {
+ pool_mode: {
+ title: 'Pool Mode',
+ type: 'string',
+ options: [
+ {
+ label: 'Transaction',
+ value: 'transaction',
+ },
+ {
+ label: 'Session',
+ value: 'session',
+ },
+ ],
},
- required: ['pool_mode'],
- type: 'object',
- }
-
- return (
- <div>
- <SchemaFormPanel
- title="Connection Pooling"
- schema={formSchema}
- model={updates}
- submitLabel="Save"
- cancelLabel="Cancel"
- onChangeModel={(model: any) => setUpdates(model)}
- onSubmit={(model: any) => updateConfig(model)}
- onReset={() => setUpdates(bouncerInfo)}
- disabled={!canUpdateConnectionPoolingConfiguration}
- disabledMessage="You need additional permissions to update connection pooling settings"
- >
- <div className="space-y-6 py-4">
- {bouncerInfo.pgbouncer_enabled && (
- <>
- <AutoField
- name="pool_mode"
- showInlineError
- errorMessage="You must select one of the two options"
- />
- <div className="!mt-1 flex" style={{ marginLeft: 'calc(33% + 0.5rem)' }}>
- <p className="text-sm text-scale-900">
- Specify when a connection can be returned to the pool. To find out the most
- suitable mode for your use case,{' '}
- <a
- className="text-green-900"
- target="_blank"
- rel="noreferrer"
- href="https://supabase.com/docs/guides/database/connecting-to-postgres#connection-pool"
- >
- click here
- </a>
- .
- </p>
- </div>
- <Divider light />
- <AutoField name="ignore_startup_parameters" />
- </>
- )}
- <Divider light />
- <Input
- className="input-mono"
- layout="horizontal"
- readOnly
- copy
- disabled
- value={connectionInfo.db_port}
- label="Port"
- />
- <Divider light />
- <Input
- className="input-mono"
- layout="vertical"
- readOnly
- copy
- disabled
- label="Connection string"
- value={
- `postgres://${connectionInfo.db_user}:[YOUR-PASSWORD]@` +
- `${connectionInfo.db_host}:${connectionInfo.db_port}` +
- `/${connectionInfo.db_name}`
- }
- />
- </div>
- </SchemaFormPanel>
- </div>
- )
+ ignore_startup_parameters: {
+ title: 'Ignore Startup Parameters',
+ type: 'string',
+ help: 'Defaults are either blank or "extra_float_digits"',
+ },
+ },
+ required: ['pool_mode'],
+ type: 'object',
}
-)
+
+ return (
+ <div>
+ <SchemaFormPanel
+ title="Connection Pooling"
+ schema={formSchema}
+ model={updates}
+ submitLabel="Save"
+ cancelLabel="Cancel"
+ onChangeModel={(model: any) => setUpdates(model)}
+ onSubmit={(model: any) => updateConfig(model)}
+ onReset={() => setUpdates(bouncerInfo)}
+ disabled={!canUpdateConnectionPoolingConfiguration}
+ disabledMessage="You need additional permissions to update connection pooling settings"
+ >
+ <div className="space-y-6 py-4">
+ {bouncerInfo.pgbouncer_enabled && (
+ <>
+ <AutoField
+ name="pool_mode"
+ showInlineError
+ errorMessage="You must select one of the two options"
+ />
+ <div className="!mt-1 flex" style={{ marginLeft: 'calc(33% + 0.5rem)' }}>
+ <p className="text-sm text-scale-900">
+ Specify when a connection can be returned to the pool. To find out the most
+ suitable mode for your use case,{' '}
+ <a
+ className="text-green-900"
+ target="_blank"
+ rel="noreferrer"
+ href="https://supabase.com/docs/guides/database/connecting-to-postgres#connection-pool"
+ >
+ click here
+ </a>
+ .
+ </p>
+ </div>
+ <Divider light />
+ <AutoField name="ignore_startup_parameters" />
+ </>
+ )}
+ <Divider light />
+ <Input
+ className="input-mono"
+ layout="horizontal"
+ readOnly
+ copy
+ disabled
+ value={connectionInfo.db_port}
+ label="Port"
+ />
+ <Divider light />
+ <Input
+ className="input-mono"
+ layout="vertical"
+ readOnly
+ copy
+ disabled
+ label="Connection string"
+ value={
+ `postgres://${connectionInfo.db_user}:[YOUR-PASSWORD]@` +
+ `${connectionInfo.db_host}:${connectionInfo.db_port}` +
+ `/${connectionInfo.db_name}`
+ }
+ />
+ </div>
+ </SchemaFormPanel>
+ </div>
+ )
+}
diff --git a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsx b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsx
index e4c254536a5..0f5bbc5360f 100644
--- a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsx
+++ b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsx
@@ -1,29 +1,25 @@
import Link from 'next/link'
-import { observer } from 'mobx-react-lite'
-import { IconAlertCircle } from 'ui'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { useProjectApiQuery } from 'data/config/project-api-query'
-import {
- CustomDomainResponse,
- useCustomDomainsQuery,
-} from 'data/custom-domains/custom-domains-query'
-import Panel from 'components/ui/Panel'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { FormHeader } from 'components/ui/Forms'
+import Panel from 'components/ui/Panel'
import UpgradeToPro from 'components/ui/UpgradeToPro'
+import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
+import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
+import { IconAlertCircle } from 'ui'
+import CustomDomainActivate from './CustomDomainActivate'
import CustomDomainDelete from './CustomDomainDelete'
import CustomDomainVerify from './CustomDomainVerify'
-import CustomDomainActivate from './CustomDomainActivate'
import CustomDomainsConfigureHostname from './CustomDomainsConfigureHostname'
import CustomDomainsShimmerLoader from './CustomDomainsShimmerLoader'
-import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
const CustomDomainConfig = () => {
- const { ui } = useStore()
+ const { project } = useProjectContext()
const { ref } = useParams()
- const tier = ui.selectedProject?.subscription_tier
+ const tier = project?.subscription_tier
const { isLoading: isSettingsLoading, data: settings } = useProjectApiQuery({
projectRef: ref,
})
@@ -103,4 +99,4 @@ const CustomDomainConfig = () => {
)
}
-export default observer(CustomDomainConfig)
+export default CustomDomainConfig
diff --git a/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectButton.tsx b/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectButton.tsx
index b1fe6d9553f..ed6215db382 100644
--- a/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectButton.tsx
+++ b/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectButton.tsx
@@ -1,24 +1,28 @@
-import { FC, useEffect, useState } from 'react'
-import { useRouter } from 'next/router'
-import { Button, Input } from 'ui'
import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQueryClient } from '@tanstack/react-query'
+import { useRouter } from 'next/router'
+import { FC, useEffect, useState } from 'react'
+import { Button, Input } from 'ui'
-import { useStore, checkPermissions } from 'hooks'
-import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
-import { delete_, post } from 'lib/common/fetch'
-import TextConfirmModal from 'components/ui/Modals/TextConfirmModal'
import { CANCELLATION_REASONS } from 'components/interfaces/BillingV2/Billing.constants'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import TextConfirmModal from 'components/ui/Modals/TextConfirmModal'
+import { invalidateProjectsQuery } from 'data/projects/projects-query'
+import { checkPermissions, useStore } from 'hooks'
+import { delete_, post } from 'lib/common/fetch'
+import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
interface Props {
type?: 'danger' | 'default'
}
const DeleteProjectButton: FC<Props> = ({ type = 'danger' }) => {
+ const queryClient = useQueryClient()
const router = useRouter()
- const { app, ui } = useStore()
+ const { ui } = useStore()
- const project = ui.selectedProject
+ const { project } = useProjectContext()
const projectRef = project?.ref
const projectTier = project?.subscription_tier ?? PRICING_TIER_PRODUCT_IDS.FREE
const isFree = projectTier === PRICING_TIER_PRODUCT_IDS.FREE
@@ -66,7 +70,7 @@ const DeleteProjectButton: FC<Props> = ({ type = 'danger' }) => {
try {
const response = await delete_(`${API_URL}/projects/${projectRef}`)
if (response.error) throw response.error
- app.onProjectDeleted(response)
+ await invalidateProjectsQuery(queryClient)
ui.setNotification({ category: 'success', message: `Successfully deleted ${project.name}` })
router.push(`/projects`)
} catch (error: any) {
diff --git a/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectPanel.tsx b/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectPanel.tsx
index 4c8c7267fdb..b05bc4d781e 100644
--- a/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectPanel.tsx
+++ b/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectPanel.tsx
@@ -1,19 +1,17 @@
import { FC } from 'react'
-import { Alert } from 'ui'
-import { useStore } from 'hooks'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { FormHeader } from 'components/ui/Forms'
import Panel from 'components/ui/Panel'
-
+import { Alert } from 'ui'
import DeleteProjectButton from './DeleteProjectButton'
-import { FormHeader } from 'components/ui/Forms'
interface Props {}
const DeleteProjectPanel: FC<Props> = ({}) => {
- const { ui } = useStore()
- const project = ui.selectedProject
+ const { project } = useProjectContext()
- if (project === undefined) return <></>
+ if (project === undefined) return null
return (
<section>
diff --git a/studio/components/interfaces/Settings/General/General.tsx b/studio/components/interfaces/Settings/General/General.tsx
index 2fce9ce289b..28a53d0c74e 100644
--- a/studio/components/interfaces/Settings/General/General.tsx
+++ b/studio/components/interfaces/Settings/General/General.tsx
@@ -1,24 +1,28 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQueryClient } from '@tanstack/react-query'
import { FC } from 'react'
import { Form, Input } from 'ui'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useStore, checkPermissions } from 'hooks'
-import { API_URL } from 'lib/constants'
-import { patch } from 'lib/common/fetch'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import {
+ FormActions,
FormHeader,
FormPanel,
- FormActions,
FormSection,
- FormSectionLabel,
FormSectionContent,
+ FormSectionLabel,
} from 'components/ui/Forms'
+import { invalidateProjectsQuery } from 'data/projects/projects-query'
+import { checkPermissions, useStore } from 'hooks'
+import { patch } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
interface Props {}
const General: FC<Props> = ({}) => {
- const { app, ui } = useStore()
- const project = ui.selectedProject
+ const queryClient = useQueryClient()
+ const { ui } = useStore()
+ const { project } = useProjectContext()
const formId = 'project-general-settings'
const initialValues = { name: project?.name ?? '', ref: project?.ref ?? '' }
@@ -37,7 +41,7 @@ const General: FC<Props> = ({}) => {
const { name } = response
resetForm({ values: { name }, initialValues: { name } })
- app.onProjectUpdated(response)
+ await invalidateProjectsQuery(queryClient)
ui.setNotification({
category: 'success',
message: 'Successfully saved settings',
diff --git a/studio/components/interfaces/Settings/General/Infrastructure/ProjectUpgradeAlert/ProjectUpgradeAlert.tsx b/studio/components/interfaces/Settings/General/Infrastructure/ProjectUpgradeAlert/ProjectUpgradeAlert.tsx
index 0af657cae0e..f216f190b1d 100644
--- a/studio/components/interfaces/Settings/General/Infrastructure/ProjectUpgradeAlert/ProjectUpgradeAlert.tsx
+++ b/studio/components/interfaces/Settings/General/Infrastructure/ProjectUpgradeAlert/ProjectUpgradeAlert.tsx
@@ -1,3 +1,4 @@
+import { useQueryClient } from '@tanstack/react-query'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { FC, useState } from 'react'
@@ -5,26 +6,28 @@ import {
Alert,
Button,
Form,
- Modal,
- IconPackage,
- Listbox,
IconAlertCircle,
IconExternalLink,
+ IconPackage,
+ Listbox,
+ Modal,
} from 'ui'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { post } from 'lib/common/fetch'
-import { API_ADMIN_URL, PROJECT_STATUS } from 'lib/constants'
import InformationBox from 'components/ui/InformationBox'
-import { BREAKING_CHANGES } from './ProjectUpgradeAlert.constants'
import { useProjectUpgradeEligibilityQuery } from 'data/config/project-upgrade-eligibility-query'
+import { invalidateProjectsQuery } from 'data/projects/projects-query'
+import { useStore } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_ADMIN_URL } from 'lib/constants'
+import { BREAKING_CHANGES } from './ProjectUpgradeAlert.constants'
interface Props {}
const ProjectUpgradeAlert: FC<Props> = ({}) => {
+ const queryClient = useQueryClient()
const router = useRouter()
- const { app, ui } = useStore()
+ const { ui } = useStore()
const { ref } = useParams()
const [showUpgradeModal, setShowUpgradeModal] = useState(false)
@@ -49,12 +52,9 @@ const ProjectUpgradeAlert: FC<Props> = ({}) => {
})
setSubmitting(false)
} else {
- const projectId = ui.selectedProject?.id
- if (projectId !== undefined) {
- app.onProjectStatusUpdated(projectId, PROJECT_STATUS.UPGRADING)
- ui.setNotification({ category: 'success', message: 'Upgrading project' })
- router.push(`/project/${ref}?upgradeInitiated=true`)
- }
+ await invalidateProjectsQuery(queryClient)
+ ui.setNotification({ category: 'success', message: 'Upgrading project' })
+ router.push(`/project/${ref}?upgradeInitiated=true`)
}
}
diff --git a/studio/components/interfaces/Support/SupportForm.tsx b/studio/components/interfaces/Support/SupportForm.tsx
index 9337a56cc63..00d71999044 100644
--- a/studio/components/interfaces/Support/SupportForm.tsx
+++ b/studio/components/interfaces/Support/SupportForm.tsx
@@ -1,36 +1,38 @@
+import { CLIENT_LIBRARIES } from 'common/constants'
+import { observer } from 'mobx-react-lite'
import Link from 'next/link'
import { useRouter } from 'next/router'
-import { useEffect, useState, FC, ChangeEvent, useRef } from 'react'
-import { observer } from 'mobx-react-lite'
+import { ChangeEvent, FC, useEffect, useRef, useState } from 'react'
import {
Button,
+ Checkbox,
+ Form,
+ IconAlertCircle,
+ IconExternalLink,
+ IconLoader,
IconMail,
IconPlus,
IconX,
Input,
Listbox,
- Form,
- IconLoader,
- IconAlertCircle,
- IconExternalLink,
- Checkbox,
} from 'ui'
-import { CLIENT_LIBRARIES } from 'common/constants'
-
-import { Project } from 'types'
-import { useStore, useFlag } from 'hooks'
-import { post, get } from 'lib/common/fetch'
-import { detectBrowser } from 'lib/helpers'
-import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
import Divider from 'components/ui/Divider'
+import InformationBox from 'components/ui/InformationBox'
import Connecting from 'components/ui/Loading'
import MultiSelect from 'components/ui/MultiSelect'
-import InformationBox from 'components/ui/InformationBox'
-import { formatMessage, uploadAttachments } from './SupportForm.utils'
-import { CATEGORY_OPTIONS, SEVERITY_OPTIONS, SERVICE_OPTIONS } from './Support.constants'
-import DisabledStateForFreeTier from './DisabledStateForFreeTier'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
import { useProfileQuery } from 'data/profile/profile-query'
+import { useProjectsQuery } from 'data/projects/projects-query'
+import { useFlag, useStore } from 'hooks'
+import useLatest from 'hooks/misc/useLatest'
+import { get, post } from 'lib/common/fetch'
+import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
+import { detectBrowser } from 'lib/helpers'
+import { Project } from 'types'
+import DisabledStateForFreeTier from './DisabledStateForFreeTier'
+import { CATEGORY_OPTIONS, SERVICE_OPTIONS, SEVERITY_OPTIONS } from './Support.constants'
+import { formatMessage, uploadAttachments } from './SupportForm.utils'
const MAX_ATTACHMENTS = 5
@@ -49,14 +51,16 @@ const SupportForm: FC<Props> = ({ setSentCategory }) => {
const [uploadedDataUrls, setUploadedDataUrls] = useState<string[]>([])
const [selectedServices, setSelectedServices] = useState<string[]>([])
- // Get all orgs and projects from global store
- const sortedOrganizations = app.organizations.list()
- const sortedProjects = app.projects.list()
+ const { data: organizations, isSuccess: isOrganizationsSuccess } = useOrganizationsQuery()
+ // for use in useEffect
+ const organizationsRef = useLatest(organizations)
+
+ const { data: allProjects, isSuccess: isProjectsSuccess } = useProjectsQuery()
- const isInitialized = app.projects.isInitialized
+ const isInitialized = isOrganizationsSuccess && isProjectsSuccess
const projectDefaults: Partial<Project>[] = [{ ref: 'no-project', name: 'No specific project' }]
- const projects = [...sortedProjects, ...projectDefaults]
+ const projects = [...(allProjects ?? []), ...projectDefaults]
const planNames = {
[PRICING_TIER_PRODUCT_IDS.FREE]: 'Free',
@@ -87,7 +91,7 @@ const SupportForm: FC<Props> = ({ setSentCategory }) => {
)
}
- const selectedProject = sortedProjects.find((project) => project.ref === ref)
+ const selectedProject = projects.find((project) => project.ref === ref)
const selectedCategory = CATEGORY_OPTIONS.find((option) => {
if (option.value.toLowerCase() === ((category as string) ?? '').toLowerCase()) return option
})
@@ -95,16 +99,16 @@ const SupportForm: FC<Props> = ({ setSentCategory }) => {
const initialProjectRef =
selectedProject !== undefined
? selectedProject.ref
- : sortedProjects.length > 0
- ? sortedProjects[0].ref
+ : projects.length > 0
+ ? projects[0].ref
: 'no-project'
const initialOrganizationSlug =
initialProjectRef !== 'no-project'
- ? sortedOrganizations.find((org) => {
- const project = sortedProjects.find((project) => project.ref === initialProjectRef)
+ ? organizations?.find((org) => {
+ const project = projects.find((project) => project.ref === initialProjectRef)
return org.id === project?.organization_id
})?.slug
- : sortedOrganizations[0]?.slug
+ : organizations?.[0]?.slug
const initialValues = {
category: selectedCategory !== undefined ? selectedCategory.value : CATEGORY_OPTIONS[0].value,
severity: 'Low',
@@ -222,13 +226,16 @@ const SupportForm: FC<Props> = ({ setSentCategory }) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
if (values.projectRef === 'no-project') {
- const updatedValues = { ...values, organizationSlug: sortedOrganizations[0]?.slug }
+ const updatedValues = {
+ ...values,
+ organizationSlug: organizationsRef.current?.[0]?.slug,
+ }
resetForm({ values: updatedValues, initialValues: updatedValues })
} else if (selectedProject) {
if (!selectedProject.subscription_tier) {
app.projects.fetchSubscriptionTier(selectedProject as Project)
}
- const organization = sortedOrganizations.find(
+ const organization = organizationsRef.current?.find(
(org) => org.id === selectedProject.organization_id
)
if (organization) {
@@ -269,9 +276,7 @@ const SupportForm: FC<Props> = ({ setSentCategory }) => {
<div className="grid grid-cols-2 gap-4">
<Listbox id="projectRef" layout="vertical" label="Which project is affected?">
{projects.map((option) => {
- const organization = sortedOrganizations.find(
- (x) => x.id === option.organization_id
- )
+ const organization = organizations?.find((x) => x.id === option.organization_id)
return (
<Listbox.Option
key={`option-${option.ref}`}
@@ -317,14 +322,14 @@ const SupportForm: FC<Props> = ({ setSentCategory }) => {
)}
</div>
- {values.projectRef === 'no-project' && sortedOrganizations.length > 0 && (
+ {values.projectRef === 'no-project' && (organizations?.length ?? 0) > 0 && (
<div className="px-6">
<Listbox
id="organizationSlug"
layout="vertical"
label="Which organization is affected?"
>
- {sortedOrganizations.map((option) => {
+ {organizations?.map((option) => {
return (
<Listbox.Option
key={`option-${option.slug}`}
@@ -353,7 +358,9 @@ const SupportForm: FC<Props> = ({ setSentCategory }) => {
Enhanced SLAs for support are available on our Enterprise Plan.
</p>
<div className="flex items-center space-x-2">
- <Link href={`/project/${values.projectRef}/settings/billing/subscription?panel=subscriptionPlan`}>
+ <Link
+ href={`/project/${values.projectRef}/settings/billing/subscription?panel=subscriptionPlan`}
+ >
<a>
<Button>Upgrade project</Button>
</a>
diff --git a/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx b/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
index 0472136abab..a204e109d2f 100644
--- a/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
+++ b/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
@@ -1,11 +1,12 @@
-import { FC } from 'react'
-import Link from 'next/link'
-import { Button, IconAlertCircle, IconCode, IconLock } from 'ui'
import * as Tooltip from '@radix-ui/react-tooltip'
import type { PostgresPolicy, PostgresTable } from '@supabase/postgres-meta'
-
-import { useStore, checkPermissions } from 'hooks'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import Link from 'next/link'
+import { FC } from 'react'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useCheckPermissions, useStore } from 'hooks'
+import { Button, IconAlertCircle, IconCode, IconLock } from 'ui'
interface Props {
table: PostgresTable
@@ -20,13 +21,14 @@ const GridHeaderActions: FC<Props> = ({
setApiPreviewPanelOpen,
refreshDocs,
}) => {
- const { ui, meta } = useStore()
- const projectRef = ui.selectedProject?.ref
+ const { meta } = useStore()
+ const { project } = useProjectContext()
+ const projectRef = project?.ref
const policies = meta.policies.list((policy: PostgresPolicy) => policy.table_id === table.id)
- const isReadOnly =
- !checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables') &&
- !checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'columns')
+ const canSqlWriteTables = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')
+ const canSqlWriteColumns = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'columns')
+ const isReadOnly = canSqlWriteTables && canSqlWriteColumns
function handlePreviewToggle() {
setApiPreviewPanelOpen(!apiPreviewPanelOpen)
diff --git a/studio/components/layouts/AccountLayout/AccountLayout.tsx b/studio/components/layouts/AccountLayout/AccountLayout.tsx
index b503f308268..f4b7599e8a6 100644
--- a/studio/components/layouts/AccountLayout/AccountLayout.tsx
+++ b/studio/components/layouts/AccountLayout/AccountLayout.tsx
@@ -1,26 +1,26 @@
import Head from 'next/head'
-import { FC, ReactNode } from 'react'
import { useRouter } from 'next/router'
-import { observer } from 'mobx-react-lite'
+import { PropsWithChildren } from 'react'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useFlag, useSelectedOrganization, withAuth } from 'hooks'
import { useSignOut } from 'lib/auth'
-import { useStore, withAuth, useFlag } from 'hooks'
import { IS_PLATFORM } from 'lib/constants'
-import WithSidebar from './WithSidebar'
import { SidebarSection } from './AccountLayout.types'
+import WithSidebar from './WithSidebar'
-interface Props {
+export interface AccountLayoutProps {
title: string
breadcrumbs: {
key: string
label: string
}[]
- children: ReactNode
}
-const AccountLayout: FC<Props> = ({ children, title, breadcrumbs }) => {
+const AccountLayout = ({ children, title, breadcrumbs }: PropsWithChildren<AccountLayoutProps>) => {
const router = useRouter()
- const { app, ui } = useStore()
+ const { data: organizations } = useOrganizationsQuery()
+ const selectedOrganization = useSelectedOrganization()
const ongoingIncident = useFlag('ongoingIncident')
const maxHeight = ongoingIncident ? 'calc(100vh - 44px)' : '100vh'
@@ -32,11 +32,10 @@ const AccountLayout: FC<Props> = ({ children, title, breadcrumbs }) => {
await router.push('/sign-in')
}
- const organizationsLinks = app.organizations
- .list()
+ const organizationsLinks = (organizations ?? [])
.map((organization) => ({
isActive:
- router.pathname.startsWith('/org/') && ui.selectedOrganization?.slug === organization.slug,
+ router.pathname.startsWith('/org/') && selectedOrganization?.slug === organization.slug,
label: organization.name + (organization.subscription_id ? ' (V2)' : ''),
href: `/org/${organization.slug}/general`,
key: organization.slug,
@@ -147,6 +146,6 @@ const AccountLayout: FC<Props> = ({ children, title, breadcrumbs }) => {
)
}
-export default withAuth(observer(AccountLayout))
+export default withAuth(AccountLayout)
-export const AccountLayoutWithoutAuth = observer(AccountLayout)
+export const AccountLayoutWithoutAuth = AccountLayout
diff --git a/studio/components/layouts/AuthLayout/AuthLayout.tsx b/studio/components/layouts/AuthLayout/AuthLayout.tsx
index 8acef13d526..b5d7248ab75 100644
--- a/studio/components/layouts/AuthLayout/AuthLayout.tsx
+++ b/studio/components/layouts/AuthLayout/AuthLayout.tsx
@@ -1,11 +1,11 @@
-import { FC, ReactNode, useState, useEffect } from 'react'
import { observer } from 'mobx-react-lite'
import { useRouter } from 'next/router'
+import { FC, ReactNode, useEffect, useState } from 'react'
-import ProjectLayout from '../'
-import { useStore, withAuth } from 'hooks'
import Error from 'components/ui/Error'
import ProductMenu from 'components/ui/ProductMenu'
+import { useSelectedProject, useStore, withAuth } from 'hooks'
+import ProjectLayout from '../'
import { generateAuthMenu } from './AuthLayout.utils'
interface Props {
@@ -14,9 +14,10 @@ interface Props {
}
const AuthLayout: FC<Props> = ({ title, children }) => {
- const { ui, meta } = useStore()
+ const { meta } = useStore()
const { isInitialized, isLoading, error } = meta.tables
- const projectRef = ui.selectedProject?.ref ?? 'default'
+ const selectedProject = useSelectedProject()
+ const projectRef = selectedProject?.ref ?? 'default'
const router = useRouter()
const page = router.pathname.split('/')[4]
@@ -24,13 +25,13 @@ const AuthLayout: FC<Props> = ({ title, children }) => {
const [loaded, setLoaded] = useState<boolean>(isInitialized)
useEffect(() => {
- if (ui.selectedProject?.ref) {
+ if (selectedProject?.ref) {
meta.policies.load()
meta.tables.load()
meta.roles.load()
meta.schemas.load()
}
- }, [ui.selectedProject?.ref])
+ }, [selectedProject?.ref])
useEffect(() => {
if (!isLoading && !loaded) {
diff --git a/studio/components/layouts/BillingLayout.tsx b/studio/components/layouts/BillingLayout.tsx
index 402c8b480e2..5404de66c65 100644
--- a/studio/components/layouts/BillingLayout.tsx
+++ b/studio/components/layouts/BillingLayout.tsx
@@ -1,24 +1,22 @@
import Link from 'next/link'
-import { FC, ReactNode } from 'react'
-import { useStore, withAuth } from 'hooks'
-import { observer } from 'mobx-react-lite'
-import { IconX } from 'ui'
+import { PropsWithChildren } from 'react'
import BaseLayout from 'components/layouts'
+import { useSelectedOrganization, useSelectedProject, withAuth } from 'hooks'
+import { IconX } from 'ui'
-interface Props {
- children: ReactNode
-}
+export interface BillingLayoutProps {}
-const BillingLayout: FC<Props> = ({ children }) => {
- const { ui } = useStore()
+const BillingLayout = ({ children }: PropsWithChildren<BillingLayoutProps>) => {
+ const selectedOrganization = useSelectedOrganization()
+ const selectedProject = useSelectedProject()
return (
<BaseLayout hideHeader hideIconBar>
<div className="flex h-full w-full flex-col">
{/* Header */}
<div className="flex items-center space-x-4 border-b py-4 px-5 dark:border-dark">
- <Link href={`/project/${ui.selectedProject?.ref}/settings/billing/subscription`} passHref>
+ <Link href={`/project/${selectedProject?.ref}/settings/billing/subscription`} passHref>
<a className="text-scale-900 transition-colors hover:text-scale-1200">
<IconX size={16} strokeWidth={1.5} />
</a>
@@ -27,7 +25,7 @@ const BillingLayout: FC<Props> = ({ children }) => {
<h1 className="text-sm text-scale-1200">Customize your plan</h1>
<div className="h-6 w-px bg-scale-600"></div>
<div className="flex items-center space-x-3">
- <p className="text-sm text-scale-1100">{ui.selectedOrganization?.name}</p>
+ <p className="text-sm text-scale-1100">{selectedOrganization?.name}</p>
<span className="text-scale-800">
<svg
viewBox="0 0 24 24"
@@ -43,7 +41,7 @@ const BillingLayout: FC<Props> = ({ children }) => {
<path d="M16 3.549L7.12 20.600"></path>
</svg>
</span>
- <p className="text-sm text-scale-1100">{ui.selectedProject?.name}</p>
+ <p className="text-sm text-scale-1100">{selectedProject?.name}</p>
</div>
</div>
</div>
@@ -55,4 +53,4 @@ const BillingLayout: FC<Props> = ({ children }) => {
)
}
-export default withAuth(observer(BillingLayout))
+export default withAuth(BillingLayout)
diff --git a/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx b/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx
index 6c721abe778..74360e1ef79 100644
--- a/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx
+++ b/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx
@@ -1,13 +1,13 @@
-import { FC, ReactNode, useEffect, useState } from 'react'
import { observer } from 'mobx-react-lite'
import { useRouter } from 'next/router'
+import { FC, ReactNode, useEffect, useState } from 'react'
-import { useFlag, useStore, withAuth } from 'hooks'
-import ProjectLayout from '../'
import Error from 'components/ui/Error'
import ProductMenu from 'components/ui/ProductMenu'
-import { generateDatabaseMenu } from './DatabaseMenu.utils'
+import { useFlag, useSelectedProject, useStore, withAuth } from 'hooks'
import { IS_PLATFORM } from 'lib/constants'
+import ProjectLayout from '../'
+import { generateDatabaseMenu } from './DatabaseMenu.utils'
interface Props {
title?: string
@@ -15,12 +15,12 @@ interface Props {
}
const DatabaseLayout: FC<Props> = ({ title, children }) => {
- const { meta, ui, vault, backups } = useStore()
+ const { meta, vault, backups } = useStore()
const { isLoading: isSchemasLoading } = meta.schemas
const { isLoading: isVaultLoading } = vault
const { isInitialized, error } = meta.tables
- const project = ui.selectedProject
+ const project = useSelectedProject()
const router = useRouter()
const page = router.pathname.split('/')[4]
@@ -34,7 +34,7 @@ const DatabaseLayout: FC<Props> = ({ title, children }) => {
const [loaded, setLoaded] = useState<boolean>(isInitialized)
useEffect(() => {
- if (ui.selectedProject?.ref) {
+ if (project?.ref) {
// Eventually should only load the required stores based on the pages
meta.schemas.load()
meta.tables.load()
@@ -48,13 +48,13 @@ const DatabaseLayout: FC<Props> = ({ title, children }) => {
backups.load()
}
}
- }, [ui.selectedProject?.ref])
+ }, [project?.ref])
useEffect(() => {
if (isVaultEnabled) {
vault.load()
}
- }, [ui.selectedProject?.ref, isVaultEnabled])
+ }, [project?.ref, isVaultEnabled])
// Optimization required: load logic should be at the page level
// e.g backups page is waiting for meta.tables to load finish when it doesnt even need that data
@@ -77,7 +77,10 @@ const DatabaseLayout: FC<Props> = ({ title, children }) => {
isLoading={!loaded}
product="Database"
productMenu={
- <ProductMenu page={page} menu={generateDatabaseMenu(project, foreignDataWrappersEnabled, pgNetExtensionExists)} />
+ <ProductMenu
+ page={page}
+ menu={generateDatabaseMenu(project, foreignDataWrappersEnabled, pgNetExtensionExists)}
+ />
}
>
<main style={{ maxHeight: '100vh' }} className="flex-1 overflow-y-auto">
diff --git a/studio/components/layouts/DocsLayout/DocsLayout.tsx b/studio/components/layouts/DocsLayout/DocsLayout.tsx
index a4923f56077..d14142740f2 100644
--- a/studio/components/layouts/DocsLayout/DocsLayout.tsx
+++ b/studio/components/layouts/DocsLayout/DocsLayout.tsx
@@ -1,20 +1,21 @@
-import { ReactElement, useEffect } from 'react'
import { observer } from 'mobx-react-lite'
import { useRouter } from 'next/router'
+import { ReactElement, useEffect } from 'react'
-import ProjectLayout from '../'
-import { useStore, withAuth } from 'hooks'
import Error from 'components/ui/Error'
import ProductMenu from 'components/ui/ProductMenu'
-import { generateDocsMenu } from './DocsLayout.utils'
+import { useSelectedProject, useStore, withAuth } from 'hooks'
import { PROJECT_STATUS } from 'lib/constants'
+import ProjectLayout from '../'
+import { generateDocsMenu } from './DocsLayout.utils'
function DocsLayout({ title, children }: { title: string; children: ReactElement }) {
const router = useRouter()
- const { meta, ui } = useStore()
+ const { meta } = useStore()
const { data, isLoading, error } = meta.openApi
+ const selectedProject = useSelectedProject()
- const isPaused = ui.selectedProject?.status === PROJECT_STATUS.INACTIVE
+ const isPaused = selectedProject?.status === PROJECT_STATUS.INACTIVE
const getPage = () => {
if (router.pathname.endsWith('graphiql')) return 'graphiql'
@@ -25,10 +26,10 @@ function DocsLayout({ title, children }: { title: string; children: ReactElement
}
useEffect(() => {
- if (ui.selectedProject?.ref && !isPaused) {
+ if (selectedProject?.ref && !isPaused) {
meta.openApi.load()
}
- }, [ui.selectedProject?.ref])
+ }, [selectedProject?.ref])
if (error) {
return (
@@ -38,7 +39,7 @@ function DocsLayout({ title, children }: { title: string; children: ReactElement
)
}
- const projectRef = ui.selectedProject?.ref ?? 'default'
+ const projectRef = selectedProject?.ref ?? 'default'
const tableNames = (data?.tables ?? []).map((table: any) => table.name)
const functionNames = (data?.functions ?? []).map((fn: any) => fn.name)
diff --git a/studio/components/layouts/LogsLayout/LogsLayout.tsx b/studio/components/layouts/LogsLayout/LogsLayout.tsx
index 1d889b1735f..ff331f16c4c 100644
--- a/studio/components/layouts/LogsLayout/LogsLayout.tsx
+++ b/studio/components/layouts/LogsLayout/LogsLayout.tsx
@@ -1,26 +1,25 @@
-import { PropsWithChildren } from 'react'
-import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useRouter } from 'next/router'
-import { checkPermissions, useStore, withAuth } from 'hooks'
-import ProjectLayout from '../'
+import { PropsWithChildren } from 'react'
+
import NoPermission from 'components/ui/NoPermission'
-import { generateLogsMenu } from './LogsMenu.utils'
import ProductMenu from 'components/ui/ProductMenu'
+import { useCheckPermissions, useSelectedProject, withAuth } from 'hooks'
+import ProjectLayout from '../'
+import { generateLogsMenu } from './LogsMenu.utils'
interface LogsLayoutProps {
title?: string
}
const LogsLayout = ({ title, children }: PropsWithChildren<LogsLayoutProps>) => {
- const { ui } = useStore()
const router = useRouter()
const pathArr = router.pathname.split('/')
const page = pathArr[pathArr.length - 1]
- const project = ui.selectedProject
+ const project = useSelectedProject()
- const canUseLogsExplorer = checkPermissions(PermissionAction.ANALYTICS_READ, 'logflare')
+ const canUseLogsExplorer = useCheckPermissions(PermissionAction.ANALYTICS_READ, 'logflare')
if (!canUseLogsExplorer) {
return (
@@ -45,4 +44,4 @@ const LogsLayout = ({ title, children }: PropsWithChildren<LogsLayoutProps>) =>
)
}
-export default withAuth(observer(LogsLayout))
+export default withAuth(LogsLayout)
diff --git a/studio/components/layouts/OrganizationLayout.tsx b/studio/components/layouts/OrganizationLayout.tsx
index 0b323386d03..c4479bcf785 100644
--- a/studio/components/layouts/OrganizationLayout.tsx
+++ b/studio/components/layouts/OrganizationLayout.tsx
@@ -1,18 +1,13 @@
-import { useStore } from 'hooks'
-import { observer } from 'mobx-react-lite'
-import { FC, ReactNode } from 'react'
-import { AccountLayout } from './'
+import { useSelectedOrganization } from 'hooks'
+import { PropsWithChildren } from 'react'
+import AccountLayout from './AccountLayout/AccountLayout'
-interface Props {
- children: ReactNode
-}
-
-const OrganizationLayout: FC<Props> = ({ children }) => {
- const { ui } = useStore()
+const OrganizationLayout = ({ children }: PropsWithChildren<{}>) => {
+ const selectedOrganization = useSelectedOrganization()
return (
<AccountLayout
- title={ui.selectedOrganization?.name ?? 'Supabase'}
+ title={selectedOrganization?.name ?? 'Supabase'}
breadcrumbs={[{ key: `org-settings`, label: 'Settings' }]}
>
{children}
@@ -20,4 +15,4 @@ const OrganizationLayout: FC<Props> = ({ children }) => {
)
}
-export default observer(OrganizationLayout)
+export default OrganizationLayout
diff --git a/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx b/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
index 4ec5f0064ad..834f8feb806 100644
--- a/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
+++ b/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
@@ -1,39 +1,36 @@
-import Link from 'next/link'
-import { observer } from 'mobx-react-lite'
import { useParams } from 'common'
+import Link from 'next/link'
import { Badge } from 'ui'
+import { getResourcesExceededLimits } from 'components/ui/OveragesBanner/OveragesBanner.utils'
+import { useProjectReadOnlyQuery } from 'data/config/project-read-only-query'
+import { useProjectUsageQuery } from 'data/usage/project-usage-query'
+import { useFlag, useSelectedOrganization, useSelectedProject } from 'hooks'
import { IS_PLATFORM, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
-import { useFlag, useStore } from 'hooks'
import BreadcrumbsView from './BreadcrumbsView'
-import OrgDropdown from './OrgDropdown'
-import ProjectDropdown from './ProjectDropdown'
import FeedbackDropdown from './FeedbackDropdown'
import HelpPopover from './HelpPopover'
import NotificationsPopover from './NotificationsPopover'
-import { getResourcesExceededLimits } from 'components/ui/OveragesBanner/OveragesBanner.utils'
-import { useProjectUsageQuery } from 'data/usage/project-usage-query'
-import { useProjectReadOnlyQuery } from 'data/config/project-read-only-query'
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import OrgDropdown from './OrgDropdown'
+import ProjectDropdown from './ProjectDropdown'
const LayoutHeader = ({ customHeaderComponents, breadcrumbs = [], headerBorder = true }: any) => {
- const { ui } = useStore()
- const { selectedOrganization, selectedProject } = ui
+ const selectedOrganization = useSelectedOrganization()
+ const selectedProject = useSelectedProject()
const { ref: projectRef } = useParams()
- const { project } = useProjectContext()
const { data: isReadOnlyMode } = useProjectReadOnlyQuery({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
+ projectRef: selectedProject?.ref,
+ connectionString: selectedProject?.connectionString,
})
const { data: usage } = useProjectUsageQuery({ projectRef })
const resourcesExceededLimits = getResourcesExceededLimits(usage)
const projectHasNoLimits =
- ui.selectedProject?.subscription_tier === PRICING_TIER_PRODUCT_IDS.PAYG ||
- ui.selectedProject?.subscription_tier === PRICING_TIER_PRODUCT_IDS.ENTERPRISE ||
- ui.selectedProject?.subscription_tier === PRICING_TIER_PRODUCT_IDS.TEAM
+ selectedProject?.subscription_tier === PRICING_TIER_PRODUCT_IDS.PAYG ||
+ selectedProject?.subscription_tier === PRICING_TIER_PRODUCT_IDS.ENTERPRISE ||
+ selectedProject?.subscription_tier === PRICING_TIER_PRODUCT_IDS.TEAM
const showOverUsageBadge =
useFlag('overusageBadge') &&
@@ -120,4 +117,4 @@ const LayoutHeader = ({ customHeaderComponents, breadcrumbs = [], headerBorder =
</div>
)
}
-export default observer(LayoutHeader)
+export default LayoutHeader
diff --git a/studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/NotificationRow.tsx b/studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/NotificationRow.tsx
index a523bd84c4d..a7b2c9887ae 100644
--- a/studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/NotificationRow.tsx
+++ b/studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/NotificationRow.tsx
@@ -1,17 +1,18 @@
-import dayjs from 'dayjs'
-import { FC, useState } from 'react'
-import { useQuery, useQueryClient } from '@tanstack/react-query'
import * as Tooltip from '@radix-ui/react-tooltip'
import { Notification, NotificationStatus } from '@supabase/shared-types/out/notifications'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import dayjs from 'dayjs'
+import { FC, useState } from 'react'
-import { useStore } from 'hooks'
import { notificationKeys } from 'data/notifications/keys'
-import { Project } from 'types'
-import { formatNotificationCTAText, formatNotificationText } from './NotificationRows.utils'
-import NotificationActions from './NotificationActions'
-import { get, delete_ } from 'lib/common/fetch'
+import { useProjectsQuery } from 'data/projects/projects-query'
+import { useStore } from 'hooks'
+import { delete_, get } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
+import { Project } from 'types'
import { Button, IconX } from 'ui'
+import NotificationActions from './NotificationActions'
+import { formatNotificationCTAText, formatNotificationText } from './NotificationRows.utils'
interface Props {
notification: Notification
@@ -28,10 +29,11 @@ const NotificationRow: FC<Props> = ({
onSelectRollbackMigration,
onSelectFinalizeMigration,
}) => {
- const { app, ui } = useStore()
+ const { ui } = useStore()
const queryClient = useQueryClient()
const [dismissing, setDismissing] = useState(false)
- const [project] = app.projects.list((project: Project) => project.id === notification.project_id)
+ const { data: projects } = useProjectsQuery()
+ const project = projects?.find((project) => project.id === notification.project_id)
const insertedAt = dayjs(notification.inserted_at).format('DD MMM YYYY, HH:mma')
const changelogLink = (notification.data as any).changelog_link
@@ -41,10 +43,11 @@ const NotificationRow: FC<Props> = ({
// have been removed, double check with Qiao before removing.
// Relevant PR: https://github.com/supabase/supabase/pull/9229
const { data: ownerReassignStatus } = useQuery(
- ['projects', project.ref, 'owner-reassign'],
- ({ signal }) => get(`${API_URL}/database/${project.ref}/owner-reassign`, { signal }),
+ ['projects', project?.ref, 'owner-reassign'],
+ ({ signal }) => get(`${API_URL}/database/${project?.ref}/owner-reassign`, { signal }),
{
- enabled: (notification.data as any).upgrade_type === 'schema-migration',
+ enabled:
+ (notification.data as any).upgrade_type === 'schema-migration' && project !== undefined,
}
)
@@ -65,6 +68,8 @@ const NotificationRow: FC<Props> = ({
setDismissing(false)
}
+ if (!project) return null
+
return (
<div className="flex py-2">
<div className="flex min-w-[50px] justify-center">
diff --git a/studio/components/layouts/ProjectLayout/LayoutHeader/OrgDropdown.tsx b/studio/components/layouts/ProjectLayout/LayoutHeader/OrgDropdown.tsx
index b2033eace78..5e2bfffa05f 100644
--- a/studio/components/layouts/ProjectLayout/LayoutHeader/OrgDropdown.tsx
+++ b/studio/components/layouts/ProjectLayout/LayoutHeader/OrgDropdown.tsx
@@ -1,17 +1,17 @@
-import { useRouter } from 'next/router'
import { toJS } from 'mobx'
-import { observer } from 'mobx-react-lite'
-import { Button, Dropdown, IconPlus } from 'ui'
+import { useRouter } from 'next/router'
-import { useFlag, useStore } from 'hooks'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useFlag, useSelectedOrganization, useStore } from 'hooks'
import { IS_PLATFORM } from 'lib/constants'
+import { Button, Dropdown, IconPlus } from 'ui'
const OrgDropdown = () => {
const router = useRouter()
- const { app, ui } = useStore()
+ const { ui } = useStore()
- const sortedOrganizations: any[] = app.organizations.list()
- const selectedOrganization: any = ui.selectedOrganization
+ const { data: organizations } = useOrganizationsQuery()
+ const selectedOrganization = useSelectedOrganization()
const orgCreationV2 = useFlag('orgcreationv2')
@@ -21,8 +21,8 @@ const OrgDropdown = () => {
align="start"
overlay={
<>
- {sortedOrganizations
- .sort((a, b) => a.name.localeCompare(b.name))
+ {organizations
+ ?.sort((a, b) => a.name.localeCompare(b.name))
.map((x) => {
const slug = toJS(x.slug)
@@ -68,14 +68,14 @@ const OrgDropdown = () => {
}
>
<Button asChild type="text" size="tiny">
- <span>{selectedOrganization.name}</span>
+ <span>{selectedOrganization?.name}</span>
</Button>
</Dropdown>
) : (
<Button asChild type="text" size="tiny">
- <span>{selectedOrganization.name}</span>
+ <span>{selectedOrganization?.name}</span>
</Button>
)
}
-export default observer(OrgDropdown)
+export default OrgDropdown
diff --git a/studio/components/layouts/ProjectLayout/LayoutHeader/ProjectDropdown.tsx b/studio/components/layouts/ProjectLayout/LayoutHeader/ProjectDropdown.tsx
index 1f685d4ca6f..33675052915 100644
--- a/studio/components/layouts/ProjectLayout/LayoutHeader/ProjectDropdown.tsx
+++ b/studio/components/layouts/ProjectLayout/LayoutHeader/ProjectDropdown.tsx
@@ -1,10 +1,10 @@
import Link from 'next/link'
-import { observer } from 'mobx-react-lite'
-import { Button, Dropdown, IconPlus, Popover } from 'ui'
import { useRouter } from 'next/router'
import { ParsedUrlQuery } from 'querystring'
+import { Button, Dropdown, IconPlus, Popover } from 'ui'
-import { useStore } from 'hooks'
+import { useProjectsQuery } from 'data/projects/projects-query'
+import { useSelectedOrganization, useSelectedProject } from 'hooks'
import { IS_PLATFORM, PROJECT_STATUS } from 'lib/constants'
// [Fran] the idea is to let users change projects without losing the current page,
@@ -31,10 +31,10 @@ const sanitizeRoute = (route: string, routerQueries: ParsedUrlQuery) => {
}
const ProjectDropdown = () => {
- const { app, ui } = useStore()
- const selectedOrganizationProjects = app.projects.list()
- const selectedOrganizationSlug = ui.selectedOrganization?.slug
- const selectedProject: any = ui.selectedProject
+ const selectedOrganization = useSelectedOrganization()
+ const selectedProject = useSelectedProject()
+ const { data: allProjects } = useProjectsQuery()
+ const selectedOrganizationSlug = selectedOrganization?.slug
const router = useRouter()
const sanitizedRoute = sanitizeRoute(router.route, router.query)
@@ -44,10 +44,10 @@ const ProjectDropdown = () => {
align="start"
overlay={
<>
- {selectedOrganizationProjects
- .filter((x: any) => x.status !== PROJECT_STATUS.INACTIVE)
- .sort((a: any, b: any) => a.name.localeCompare(b.name))
- .map((x: any) => (
+ {allProjects
+ ?.filter((x) => x.status !== PROJECT_STATUS.INACTIVE)
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .map((x) => (
<Link
key={x.ref}
href={sanitizedRoute?.replace('[ref]', x.ref) ?? `/project/${x.ref}`}
@@ -56,7 +56,7 @@ const ProjectDropdown = () => {
<a className="block">
<Dropdown.Item
className={
- selectedProject.name === x.name
+ selectedProject?.name === x.name
? 'font-bold bg-slate-400 dark:bg-slate-500'
: ''
}
@@ -76,14 +76,14 @@ const ProjectDropdown = () => {
}
>
<Button asChild type="text" size="tiny" className="my-1">
- <span>{selectedProject.name}</span>
+ <span>{selectedProject?.name}</span>
</Button>
</Dropdown>
) : (
<Button asChild type="text" size="tiny">
- <span>{selectedProject.name}</span>
+ <span>{selectedProject?.name}</span>
</Button>
)
}
-export default observer(ProjectDropdown)
+export default ProjectDropdown
diff --git a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx
index 944df1f6c25..50bdff1621b 100644
--- a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx
+++ b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx
@@ -1,46 +1,46 @@
-import Link from 'next/link'
-import { FC } from 'react'
+import * as Tooltip from '@radix-ui/react-tooltip'
import { isUndefined } from 'lodash'
-import { observer } from 'mobx-react-lite'
+import Link from 'next/link'
import { useRouter } from 'next/router'
+import { FC } from 'react'
+
+import { useTheme } from 'common'
+import { useParams } from 'common/hooks'
+import { useFlag } from 'hooks'
+import { IS_PLATFORM } from 'lib/constants'
+import { detectOS } from 'lib/helpers'
import {
Button,
Dropdown,
+ IconCommand,
IconHome,
+ IconSearch,
IconSettings,
IconUser,
- IconSearch,
useCommandMenu,
- IconCommand,
} from 'ui'
-import * as Tooltip from '@radix-ui/react-tooltip'
-import { useFlag, useStore } from 'hooks'
-import { IS_PLATFORM } from 'lib/constants'
+import { useProjectContext } from '../ProjectContext'
import {
generateOtherRoutes,
generateProductRoutes,
generateToolRoutes,
} from './NavigationBar.utils'
import NavigationIconButton from './NavigationIconButton'
-import { useParams } from 'common/hooks'
-import { useTheme } from 'common'
-import { detectOS } from 'lib/helpers'
interface Props {}
const NavigationBar: FC<Props> = ({}) => {
const router = useRouter()
- const { ui } = useStore()
const { isDarkMode, toggleTheme } = useTheme()
const { ref: projectRef } = useParams()
- const projectBaseInfo = ui.selectedProjectBaseInfo
+ const { project } = useProjectContext()
const ongoingIncident = useFlag('ongoingIncident')
const activeRoute = router.pathname.split('/')[3]
- const toolRoutes = generateToolRoutes(projectRef, projectBaseInfo)
- const productRoutes = generateProductRoutes(projectRef, projectBaseInfo)
- const otherRoutes = generateOtherRoutes(projectRef, projectBaseInfo)
+ const toolRoutes = generateToolRoutes(projectRef, project)
+ const productRoutes = generateProductRoutes(projectRef, project)
+ const otherRoutes = generateOtherRoutes(projectRef, project)
const showCmdkHelper = useFlag('dashboardCmdk')
const os = detectOS()
const { setIsOpen } = useCommandMenu()
@@ -172,4 +172,4 @@ const NavigationBar: FC<Props> = ({}) => {
)
}
-export default observer(NavigationBar)
+export default NavigationBar
diff --git a/studio/components/layouts/ProjectLayout/ProjectContext.tsx b/studio/components/layouts/ProjectLayout/ProjectContext.tsx
index 8fc28f52926..fd20266e468 100644
--- a/studio/components/layouts/ProjectLayout/ProjectContext.tsx
+++ b/studio/components/layouts/ProjectLayout/ProjectContext.tsx
@@ -1,8 +1,7 @@
import { useParams } from 'common/hooks'
-import { useStore } from 'hooks'
+import { useSelectedProject } from 'hooks'
import { PROJECT_STATUS } from 'lib/constants'
-import { observer } from 'mobx-react-lite'
-import { createContext, PropsWithChildren, useContext, useMemo } from 'react'
+import { PropsWithChildren, createContext, useContext, useMemo } from 'react'
import { Project } from 'types'
type ProjectContextType = {
@@ -23,29 +22,28 @@ type ProjectContextProviderProps = {
projectRef: string | undefined
}
-export const ProjectContextProvider = observer(
- ({ projectRef, children }: PropsWithChildren<ProjectContextProviderProps>) => {
- // TODO(alaister): This will eventually be replaced with a react-query query
- // once we remove mobx
- const { ui } = useStore()
-
- const value = useMemo<ProjectContextType>(() => {
- if (ui.selectedProject?.ref === projectRef) {
- return {
- project: ui.selectedProject,
- isLoading: false,
- }
- }
+export const ProjectContextProvider = ({
+ projectRef,
+ children,
+}: PropsWithChildren<ProjectContextProviderProps>) => {
+ const selectedProject = useSelectedProject()
+ const value = useMemo<ProjectContextType>(() => {
+ if (selectedProject?.ref === projectRef) {
return {
- project: undefined,
- isLoading: true,
+ project: selectedProject,
+ isLoading: false,
}
- }, [ui.selectedProject?.ref, projectRef])
+ }
+
+ return {
+ project: undefined,
+ isLoading: true,
+ }
+ }, [selectedProject, projectRef])
- return <ProjectContext.Provider value={value}>{children}</ProjectContext.Provider>
- }
-)
+ return <ProjectContext.Provider value={value}>{children}</ProjectContext.Provider>
+}
export const ProjectContextFromParamsProvider = ({ children }: PropsWithChildren<{}>) => {
const { ref: projectRef } = useParams()
diff --git a/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
index f00bbca7e2a..4bf38e4c26c 100644
--- a/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
+++ b/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
@@ -1,22 +1,21 @@
import Head from 'next/head'
-import { ReactNode, Fragment } from 'react'
-import { observer } from 'mobx-react-lite'
import { useRouter } from 'next/router'
-import { useStore, withAuth, useFlag } from 'hooks'
-import { useParams } from 'common/hooks'
-import { PROJECT_STATUS } from 'lib/constants'
+import { Fragment, ReactNode } from 'react'
+import { useParams } from 'common/hooks'
import Connecting from 'components/ui/Loading'
-import NavigationBar from './NavigationBar/NavigationBar'
-import ProductMenuBar from './ProductMenuBar'
-import LayoutHeader from './LayoutHeader'
+import { useFlag, useSelectedOrganization, useSelectedProject, withAuth } from 'hooks'
+import { PROJECT_STATUS } from 'lib/constants'
+import BuildingState from './BuildingState'
import ConnectingState from './ConnectingState'
+import LayoutHeader from './LayoutHeader'
+import NavigationBar from './NavigationBar/NavigationBar'
import PausingState from './PausingState'
-import BuildingState from './BuildingState'
+import ProductMenuBar from './ProductMenuBar'
import { ProjectContextProvider } from './ProjectContext'
+import ProjectPausedState from './ProjectPausedState'
import RestoringState from './RestoringState'
import UpgradingState from './UpgradingState'
-import ProjectPausedState from './ProjectPausedState'
export interface ProjectLayoutProps {
title?: string
@@ -39,14 +38,15 @@ const ProjectLayout = ({
hideIconBar = false,
selectedTable,
}: ProjectLayoutProps) => {
- const { ui } = useStore()
const router = useRouter()
const { ref: projectRef } = useParams()
const ongoingIncident = useFlag('ongoingIncident')
- const projectName = ui.selectedProject?.name
- const organizationName = ui.selectedOrganization?.name
+ const selectedOrganization = useSelectedOrganization()
+ const selectedProject = useSelectedProject()
+ const projectName = selectedProject?.name
+ const organizationName = selectedOrganization?.name
- const isPaused = ui.selectedProject?.status === PROJECT_STATUS.INACTIVE
+ const isPaused = selectedProject?.status === PROJECT_STATUS.INACTIVE
const ignorePausedState =
router.pathname === '/project/[ref]' || router.pathname.includes('/project/[ref]/settings')
const showPausedState = isPaused && !ignorePausedState
@@ -98,9 +98,9 @@ const ProjectLayout = ({
)
}
-export const ProjectLayoutWithAuth = withAuth(observer(ProjectLayout))
+export const ProjectLayoutWithAuth = withAuth(ProjectLayout)
-export default observer(ProjectLayout)
+export default ProjectLayout
interface MenuBarWrapperProps {
isLoading: boolean
@@ -108,10 +108,10 @@ interface MenuBarWrapperProps {
children: ReactNode
}
-const MenuBarWrapper = observer(({ isLoading, productMenu, children }: MenuBarWrapperProps) => {
- const { ui } = useStore()
- return <>{!isLoading && productMenu && ui.selectedProject !== undefined ? children : null}</>
-})
+const MenuBarWrapper = ({ isLoading, productMenu, children }: MenuBarWrapperProps) => {
+ const selectedProject = useSelectedProject()
+ return <>{!isLoading && productMenu && selectedProject !== undefined ? children : null}</>
+}
interface ContentWrapperProps {
isLoading: boolean
@@ -130,8 +130,8 @@ interface ContentWrapperProps {
*
* [TODO] Next iteration should scrape long polling and just listen to the project's status
*/
-const ContentWrapper = observer(({ isLoading, children }: ContentWrapperProps) => {
- const { ui } = useStore()
+const ContentWrapper = ({ isLoading, children }: ContentWrapperProps) => {
+ const selectedProject = useSelectedProject()
const router = useRouter()
const routesToIgnorePostgrestConnection = [
@@ -140,95 +140,93 @@ const ContentWrapper = observer(({ isLoading, children }: ContentWrapperProps) =
'/project/[ref]/settings/database',
'/project/[ref]/settings/billing/subscription',
'/project/[ref]/settings/billing/usage',
- '/project/[ref]/settings/billing/invoices'
+ '/project/[ref]/settings/billing/invoices',
]
const requiresDbConnection: boolean = router.pathname !== '/project/[ref]/settings/general'
const requiresPostgrestConnection = !routesToIgnorePostgrestConnection.includes(router.pathname)
- const isProjectUpgrading = ui.selectedProject?.status === PROJECT_STATUS.UPGRADING
- const isProjectRestoring = ui.selectedProject?.status === PROJECT_STATUS.RESTORING
- const isProjectBuilding = ui.selectedProject?.status === PROJECT_STATUS.COMING_UP
- const isProjectPausing = ui.selectedProject?.status === PROJECT_STATUS.GOING_DOWN
- const isProjectOffline = ui.selectedProject?.postgrestStatus === 'OFFLINE'
+ const isProjectUpgrading = selectedProject?.status === PROJECT_STATUS.UPGRADING
+ const isProjectRestoring = selectedProject?.status === PROJECT_STATUS.RESTORING
+ const isProjectBuilding = selectedProject?.status === PROJECT_STATUS.COMING_UP
+ const isProjectPausing = selectedProject?.status === PROJECT_STATUS.GOING_DOWN
+ const isProjectOffline = selectedProject?.postgrestStatus === 'OFFLINE'
return (
<>
- {isLoading || ui.selectedProject === undefined ? (
+ {isLoading || selectedProject === undefined ? (
<Connecting />
) : isProjectUpgrading ? (
<UpgradingState />
) : isProjectPausing ? (
- <PausingState project={ui.selectedProject} />
+ <PausingState project={selectedProject} />
) : requiresPostgrestConnection && isProjectOffline ? (
- <ConnectingState project={ui.selectedProject} />
+ <ConnectingState project={selectedProject} />
) : requiresDbConnection && isProjectRestoring ? (
<RestoringState />
) : requiresDbConnection && isProjectBuilding ? (
- <BuildingState project={ui.selectedProject} />
+ <BuildingState project={selectedProject} />
) : (
- <Fragment key={ui.selectedProject.ref}>{children}</Fragment>
+ <Fragment key={selectedProject.ref}>{children}</Fragment>
)}
</>
)
-})
+}
/**
* Shows the children irregardless of whether the selected project has loaded or not
* We'll eventually want to use this instead of the current ProjectLayout to prevent
* a catch-all spinner on the dashboard
*/
-export const ProjectLayoutNonBlocking = observer(
- ({
- title,
- product = '',
- productMenu,
- children,
- hideHeader = false,
- hideIconBar = false,
- }: ProjectLayoutProps) => {
- const { ui } = useStore()
- const router = useRouter()
- const { ref: projectRef } = useParams()
- const ongoingIncident = useFlag('ongoingIncident')
- const isPaused = ui.selectedProject?.status === PROJECT_STATUS.INACTIVE
- const ignorePausedState =
- router.pathname === '/project/[ref]' || router.pathname.includes('/project/[ref]/settings')
- const showPausedState = isPaused && !ignorePausedState
-
- return (
- <ProjectContextProvider projectRef={projectRef}>
- <Head>
- <title>{title ? `${title} | Supabase` : 'Supabase'}</title>
- <meta name="description" content="Supabase Studio" />
- <link rel="icon" href="/favicon.ico" />
- </Head>
- <div className="flex h-full">
- {/* Left-most navigation side bar to access products */}
- {!hideIconBar && <NavigationBar />}
-
- {/* Product menu bar */}
- {productMenu && !showPausedState && (
- <ProductMenuBar title={product}>{productMenu}</ProductMenuBar>
- )}
+export const ProjectLayoutNonBlocking = ({
+ title,
+ product = '',
+ productMenu,
+ children,
+ hideHeader = false,
+ hideIconBar = false,
+}: ProjectLayoutProps) => {
+ const selectedProject = useSelectedProject()
+ const router = useRouter()
+ const { ref: projectRef } = useParams()
+ const ongoingIncident = useFlag('ongoingIncident')
+ const isPaused = selectedProject?.status === PROJECT_STATUS.INACTIVE
+ const ignorePausedState =
+ router.pathname === '/project/[ref]' || router.pathname.includes('/project/[ref]/settings')
+ const showPausedState = isPaused && !ignorePausedState
- <main
- className="flex w-full flex-1 flex-col overflow-x-hidden"
- style={{ height: ongoingIncident ? 'calc(100vh - 44px)' : '100vh' }}
- >
- {!hideHeader && <LayoutHeader />}
- {showPausedState ? (
- <div className="mx-auto my-16 w-full h-full max-w-7xl flex items-center">
- <div className="w-full">
- <ProjectPausedState product={product} />
- </div>
+ return (
+ <ProjectContextProvider projectRef={projectRef}>
+ <Head>
+ <title>{title ? `${title} | Supabase` : 'Supabase'}</title>
+ <meta name="description" content="Supabase Studio" />
+ <link rel="icon" href="/favicon.ico" />
+ </Head>
+ <div className="flex h-full">
+ {/* Left-most navigation side bar to access products */}
+ {!hideIconBar && <NavigationBar />}
+
+ {/* Product menu bar */}
+ {productMenu && !showPausedState && (
+ <ProductMenuBar title={product}>{productMenu}</ProductMenuBar>
+ )}
+
+ <main
+ className="flex w-full flex-1 flex-col overflow-x-hidden"
+ style={{ height: ongoingIncident ? 'calc(100vh - 44px)' : '100vh' }}
+ >
+ {!hideHeader && <LayoutHeader />}
+ {showPausedState ? (
+ <div className="mx-auto my-16 w-full h-full max-w-7xl flex items-center">
+ <div className="w-full">
+ <ProjectPausedState product={product} />
</div>
- ) : (
- children
- )}
- </main>
- </div>
- </ProjectContextProvider>
- )
- }
-)
+ </div>
+ ) : (
+ children
+ )}
+ </main>
+ </div>
+ </ProjectContextProvider>
+ )
+}
diff --git a/studio/components/layouts/ProjectLayout/ProjectPausedState.tsx b/studio/components/layouts/ProjectLayout/ProjectPausedState.tsx
index 3bc5d3a4bd4..91d206b540e 100644
--- a/studio/components/layouts/ProjectLayout/ProjectPausedState.tsx
+++ b/studio/components/layouts/ProjectLayout/ProjectPausedState.tsx
@@ -1,25 +1,30 @@
-import Link from 'next/link'
-import { useState } from 'react'
import * as Tooltip from '@radix-ui/react-tooltip'
-import { Modal, Button, IconPauseCircle } from 'ui'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQueryClient } from '@tanstack/react-query'
+import Link from 'next/link'
+import { useState } from 'react'
-import { checkPermissions, useStore, useFlag } from 'hooks'
-import { post } from 'lib/common/fetch'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
+import { useParams } from 'common'
import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'
import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'
-import { useParams } from 'common'
+import { invalidateOrganizationsQuery } from 'data/organizations/organizations-query'
+import { checkPermissions, useFlag, useSelectedOrganization, useStore } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { Button, IconPauseCircle, Modal } from 'ui'
+import { useProjectContext } from './ProjectContext'
export interface ProjectPausedStateProps {
product?: string
}
const ProjectPausedState = ({ product }: ProjectPausedStateProps) => {
- const { ui, app } = useStore()
+ const queryClient = useQueryClient()
+ const { ui } = useStore()
const { ref } = useParams()
- const project = ui.selectedProject
- const orgSlug = ui.selectedOrganization?.slug
+ const selectedOrganization = useSelectedOrganization()
+ const { project } = useProjectContext()
+ const orgSlug = selectedOrganization?.slug
const kpsEnabled = useFlag('initWithKps')
const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery({ slug: orgSlug })
@@ -53,7 +58,7 @@ const ProjectPausedState = ({ product }: ProjectPausedStateProps) => {
}
await post(`${API_URL}/projects/${project.ref}/restore`, { kps_enabled: kpsEnabled })
- app.onProjectUpdated({ ...project, status: PROJECT_STATUS.RESTORING })
+ await invalidateOrganizationsQuery(queryClient)
ui.setNotification({ category: 'success', message: 'Restoring project' })
}
diff --git a/studio/components/layouts/ProjectLayout/RestoringState.tsx b/studio/components/layouts/ProjectLayout/RestoringState.tsx
index ce1e8130d45..8c40d1c716f 100644
--- a/studio/components/layouts/ProjectLayout/RestoringState.tsx
+++ b/studio/components/layouts/ProjectLayout/RestoringState.tsx
@@ -1,16 +1,17 @@
import Link from 'next/link'
import { FC, useEffect, useRef, useState } from 'react'
-import { Button, IconAlertCircle, IconCheckCircle, IconLoader } from 'ui'
import { useStore } from 'hooks'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
import { getWithTimeout } from 'lib/common/fetch'
+import { API_URL, PROJECT_STATUS } from 'lib/constants'
+import { Button, IconAlertCircle, IconCheckCircle, IconLoader } from 'ui'
+import { useProjectContext } from './ProjectContext'
interface Props {}
const RestoringState: FC<Props> = ({}) => {
const { app, ui, meta } = useStore()
- const project = ui.selectedProject
+ const { project } = useProjectContext()
const checkServerInterval = useRef<number>()
const [loading, setLoading] = useState(false)
diff --git a/studio/components/layouts/ProjectLayout/UpgradingState/UpgradingState.tsx b/studio/components/layouts/ProjectLayout/UpgradingState/UpgradingState.tsx
index 0ec3881d623..9436938f079 100644
--- a/studio/components/layouts/ProjectLayout/UpgradingState/UpgradingState.tsx
+++ b/studio/components/layouts/ProjectLayout/UpgradingState/UpgradingState.tsx
@@ -20,23 +20,24 @@ import { useParams } from 'common/hooks'
import { IS_PLATFORM } from 'lib/constants'
import { DATABASE_UPGRADE_MESSAGES } from './UpgradingState.constants'
import { useProjectUpgradingStatusQuery } from 'data/config/project-upgrade-status-query'
+import { useProjectContext } from '../ProjectContext'
const UpgradingState = () => {
const { ref } = useParams()
- const { app, ui, meta } = useStore()
+ const { app, meta } = useStore()
+ const { project } = useProjectContext()
const [loading, setLoading] = useState(false)
const [isExpanded, setIsExpanded] = useState(false)
const { data } = useProjectUpgradingStatusQuery(
{
projectRef: ref,
- projectStatus: ui.selectedProject?.status,
+ projectStatus: project?.status,
},
{
enabled: IS_PLATFORM,
}
)
- const project = ui.selectedProject
const { initiated_at, status, progress, target_version, error } =
data?.databaseUpgradeStatus ?? {}
const progressStage = Number((progress || '').split('_')[0])
diff --git a/studio/components/layouts/ReportsLayout/ReportsLayout.tsx b/studio/components/layouts/ReportsLayout/ReportsLayout.tsx
index 6c789413f9e..f1517357776 100644
--- a/studio/components/layouts/ReportsLayout/ReportsLayout.tsx
+++ b/studio/components/layouts/ReportsLayout/ReportsLayout.tsx
@@ -1,9 +1,9 @@
-import { PropsWithChildren } from 'react'
-import { observer } from 'mobx-react-lite'
import { useRouter } from 'next/router'
-import { useStore, withAuth } from 'hooks'
-import ProjectLayout from '../'
+import { PropsWithChildren } from 'react'
+
import ProductMenu from 'components/ui/ProductMenu'
+import { useSelectedProject, withAuth } from 'hooks'
+import ProjectLayout from '../'
import { generateReportsMenu } from './ReportsMenu.utils'
interface ReportsLayoutProps {
@@ -11,10 +11,9 @@ interface ReportsLayoutProps {
}
const ReportsLayout = ({ title, children }: PropsWithChildren<ReportsLayoutProps>) => {
- const { ui } = useStore()
const router = useRouter()
- const project = ui.selectedProject
+ const project = useSelectedProject()
const page = router.pathname.split('/')[4] || ''
return (
@@ -30,4 +29,4 @@ const ReportsLayout = ({ title, children }: PropsWithChildren<ReportsLayoutProps
)
}
-export default withAuth(observer(ReportsLayout))
+export default withAuth(ReportsLayout)
diff --git a/studio/components/layouts/SettingsLayout/SettingsLayout.tsx b/studio/components/layouts/SettingsLayout/SettingsLayout.tsx
index 983a2c67393..4c4d2425c38 100644
--- a/studio/components/layouts/SettingsLayout/SettingsLayout.tsx
+++ b/studio/components/layouts/SettingsLayout/SettingsLayout.tsx
@@ -1,7 +1,7 @@
import { FC, ReactNode, useEffect } from 'react'
import { observer } from 'mobx-react-lite'
import { useRouter } from 'next/router'
-import { useFlag, useStore, withAuth } from 'hooks'
+import { useFlag, useSelectedProject, useStore, withAuth } from 'hooks'
import { generateSettingsMenu } from './SettingsMenu.utils'
import ProjectLayout from '../'
@@ -14,8 +14,7 @@ interface Props {
const SettingsLayout: FC<Props> = ({ title, children }) => {
const { ui, meta } = useStore()
- const projectRef = ui.selectedProjectRef as string
- const projectBaseInfo = ui.selectedProjectBaseInfo
+ const project = useSelectedProject()
const router = useRouter()
// billing pages live under /billing/invoices and /billing/subscription, etc
@@ -25,13 +24,13 @@ const SettingsLayout: FC<Props> = ({ title, children }) => {
: router.pathname.split('/')[4]
const isVaultEnabled = useFlag('vaultExtension')
- const menuRoutes = generateSettingsMenu(projectRef, projectBaseInfo, isVaultEnabled)
+ const menuRoutes = generateSettingsMenu(project?.ref as string, project, isVaultEnabled)
useEffect(() => {
- if (ui.selectedProject?.ref) {
+ if (project?.ref) {
meta.extensions.load()
}
- }, [ui.selectedProject?.ref])
+ }, [project?.ref])
return (
<ProjectLayout
diff --git a/studio/components/layouts/StorageLayout/StorageLayout.tsx b/studio/components/layouts/StorageLayout/StorageLayout.tsx
index cc753c05347..b4a85a4ce73 100644
--- a/studio/components/layouts/StorageLayout/StorageLayout.tsx
+++ b/studio/components/layouts/StorageLayout/StorageLayout.tsx
@@ -1,16 +1,16 @@
-import { FC, ReactNode, useEffect } from 'react'
-import { find, filter, get as _get } from 'lodash'
+import { get as _get, filter, find } from 'lodash'
import { observer } from 'mobx-react-lite'
+import { FC, ReactNode, useEffect } from 'react'
-import { useStore, withAuth } from 'hooks'
import { useParams } from 'common/hooks'
+import DeleteBucketModal from 'components/to-be-cleaned/Storage/DeleteBucketModal'
+import { formatPoliciesForStorage } from 'components/to-be-cleaned/Storage/Storage.utils'
import { AutoApiService, useProjectApiQuery } from 'data/config/project-api-query'
+import { useSelectedProject, useStore, withAuth } from 'hooks'
+import { PROJECT_STATUS } from 'lib/constants'
+import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
import ProjectLayout from '../'
import StorageMenu from './StorageMenu'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
-import { formatPoliciesForStorage } from 'components/to-be-cleaned/Storage/Storage.utils'
-import DeleteBucketModal from 'components/to-be-cleaned/Storage/DeleteBucketModal'
-import { PROJECT_STATUS } from 'lib/constants'
interface Props {
title: string
@@ -19,6 +19,7 @@ interface Props {
const StorageLayout: FC<Props> = ({ title, children }) => {
const { ui, meta } = useStore()
+ const project = useSelectedProject()
const { ref: projectRef } = useParams()
const storageExplorerStore = useStorageStore()
const {
@@ -32,7 +33,7 @@ const StorageLayout: FC<Props> = ({ title, children }) => {
const { data: settings, isLoading } = useProjectApiQuery({ projectRef })
const apiService = settings?.autoApiService
- const isPaused = ui.selectedProject?.status === PROJECT_STATUS.INACTIVE
+ const isPaused = project?.status === PROJECT_STATUS.INACTIVE
useEffect(() => {
if (!isLoading && apiService) initializeStorageStore(apiService)
diff --git a/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx b/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx
index 60143db8f77..909a195df81 100644
--- a/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx
+++ b/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx
@@ -1,21 +1,21 @@
-import { PropsWithChildren, useEffect } from 'react'
-import { useRouter } from 'next/router'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import { noop } from 'lodash'
import { observer } from 'mobx-react-lite'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useRouter } from 'next/router'
+import { PropsWithChildren, useEffect } from 'react'
-import { checkPermissions, useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { Entity } from 'data/entity-types/entity-type-query'
-import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
-import { useIsTableLoaded, useTableEditorStateSnapshot } from 'state/table-editor'
-import ProjectLayout from '../'
-import TableEditorMenu from './TableEditorMenu'
+import Connecting from 'components/ui/Loading/Loading'
import NoPermission from 'components/ui/NoPermission'
+import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
+import { Entity } from 'data/entity-types/entity-type-query'
+import { checkPermissions, useSelectedProject, useStore } from 'hooks'
import useEntityType from 'hooks/misc/useEntityType'
-import Connecting from 'components/ui/Loading/Loading'
import useLatest from 'hooks/misc/useLatest'
+import { useIsTableLoaded, useTableEditorStateSnapshot } from 'state/table-editor'
+import ProjectLayout from '../'
import useTableRowsPrefetchWrapper from './TableEditorLayout.utils'
+import TableEditorMenu from './TableEditorMenu'
export interface TableEditorLayoutProps {
selectedSchema?: string
@@ -37,7 +37,8 @@ const TableEditorLayout = ({
onDuplicateTable = noop,
children,
}: PropsWithChildren<TableEditorLayoutProps>) => {
- const { vault, meta, ui } = useStore()
+ const { vault, meta } = useStore()
+ const selectedProject = useSelectedProject()
const router = useRouter()
const { ref, id: _id } = useParams()
const id = _id ? Number(_id) : undefined
@@ -49,14 +50,14 @@ const TableEditorLayout = ({
const isVaultEnabled = vaultExtension !== undefined && vaultExtension.installed_version !== null
useEffect(() => {
- if (ui.selectedProject?.ref) {
+ if (selectedProject?.ref) {
meta.schemas.load()
meta.types.load()
meta.policies.load()
meta.publications.load()
meta.extensions.load()
}
- }, [ui.selectedProject?.ref])
+ }, [selectedProject?.ref])
const isLoaded = useIsTableLoaded(ref, id)
@@ -112,7 +113,7 @@ const TableEditorLayout = ({
if (isVaultEnabled) {
vault.load()
}
- }, [ui.selectedProject?.ref, isVaultEnabled])
+ }, [selectedProject?.ref, isVaultEnabled])
if (!canReadTables) {
return (
diff --git a/studio/components/to-be-cleaned/Dropdown/OrganizationDropdown.js b/studio/components/to-be-cleaned/Dropdown/OrganizationDropdown.js
index c0d03ac03c9..ddfa2ba75b0 100644
--- a/studio/components/to-be-cleaned/Dropdown/OrganizationDropdown.js
+++ b/studio/components/to-be-cleaned/Dropdown/OrganizationDropdown.js
@@ -1,17 +1,11 @@
-import React from 'react'
import { useRouter } from 'next/router'
-import { toJS } from 'mobx'
-import { Button, Dropdown, IconPlus } from 'ui'
-import { observer } from 'mobx-react-lite'
+
import { useFlag } from 'hooks'
+import { Button, Dropdown, IconPlus } from 'ui'
const OrganizationDropdown = ({ organizations }) => {
const router = useRouter()
- const organizationList = Object.values(toJS(organizations.data)).sort((a, b) =>
- a.name.localeCompare(b.name)
- )
-
const orgCreationV2 = useFlag('orgcreationv2')
return (
@@ -21,7 +15,7 @@ const OrganizationDropdown = ({ organizations }) => {
overlay={
<>
<Dropdown.Label>Choose organization</Dropdown.Label>
- {organizationList
+ {organizations
.sort((a, b) => a.name.localeCompare(b.name))
.map((x) => (
<Dropdown.Item
@@ -53,4 +47,4 @@ const OrganizationDropdown = ({ organizations }) => {
</Dropdown>
)
}
-export default observer(OrganizationDropdown)
+export default OrganizationDropdown
diff --git a/studio/components/ui/UpgradeToPro.tsx b/studio/components/ui/UpgradeToPro.tsx
index fb17a75452a..e1771980505 100644
--- a/studio/components/ui/UpgradeToPro.tsx
+++ b/studio/components/ui/UpgradeToPro.tsx
@@ -1,13 +1,13 @@
-import { Button } from 'ui'
-import { observer } from 'mobx-react-lite'
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import Link from 'next/link'
import { FC, ReactNode } from 'react'
-import * as Tooltip from '@radix-ui/react-tooltip'
-import { checkPermissions, useStore, useFlag } from 'hooks'
import { useParams } from 'common/hooks'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { checkPermissions, useFlag } from 'hooks'
import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { Button } from 'ui'
interface Props {
icon?: ReactNode
@@ -17,9 +17,9 @@ interface Props {
}
const UpgradeToPro: FC<Props> = ({ icon, primaryText, projectRef, secondaryText }) => {
- const { ui } = useStore()
const { ref } = useParams()
- const tier = ui.selectedProject?.subscription_tier
+ const { project } = useProjectContext()
+ const tier = project?.subscription_tier
const canUpdateSubscription = checkPermissions(
PermissionAction.BILLING_WRITE,
@@ -93,4 +93,4 @@ const UpgradeToPro: FC<Props> = ({ icon, primaryText, projectRef, secondaryText
)
}
-export default observer(UpgradeToPro)
+export default UpgradeToPro
diff --git a/studio/data/organizations/organizations-query.ts b/studio/data/organizations/organizations-query.ts
index 598c8b17df4..72dc26b52b6 100644
--- a/studio/data/organizations/organizations-query.ts
+++ b/studio/data/organizations/organizations-query.ts
@@ -1,4 +1,4 @@
-import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
+import { QueryClient, useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
import { get } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import { useCallback } from 'react'
@@ -7,11 +7,13 @@ import { organizationKeys } from './keys'
export type OrganizationsResponse = Organization[]
-export async function getOrganizations(signal?: AbortSignal) {
+export async function getOrganizations(signal?: AbortSignal): Promise<OrganizationsResponse> {
const data = await get(`${API_URL}/organizations`, { signal })
if (data.error) throw data.error
- return data as OrganizationsResponse
+ const sorted = (data as Organization[]).sort((a, b) => a.name.localeCompare(b.name))
+
+ return sorted
}
export type OrganizationsData = Awaited<ReturnType<typeof getOrganizations>>
@@ -35,3 +37,7 @@ export const useOrganizationsPrefetch = () => {
[]
)
}
+
+export function invalidateOrganizationsQuery(client: QueryClient) {
+ return client.invalidateQueries(organizationKeys.list())
+}
diff --git a/studio/data/projects/projects-query.ts b/studio/data/projects/projects-query.ts
index 7429a1fd7c5..eb31d0f5d69 100644
--- a/studio/data/projects/projects-query.ts
+++ b/studio/data/projects/projects-query.ts
@@ -1,7 +1,8 @@
-import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
+import { QueryClient, useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
+import { useCallback, useRef } from 'react'
+
import { get } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
-import { useCallback } from 'react'
import { Project } from 'types'
import { projectKeys } from './keys'
@@ -28,10 +29,28 @@ export const useProjectsQuery = <TData = ProjectsData>({
{ enabled: enabled, ...options }
)
-export const useProjectsPrefetch = () => {
+export function prefetchProjects(client: QueryClient) {
+ return client.prefetchQuery(projectKeys.list(), ({ signal }) => getProjects(signal))
+}
+
+export function useProjectsPrefetch() {
const client = useQueryClient()
return useCallback(() => {
- client.prefetchQuery(projectKeys.list(), ({ signal }) => getProjects(signal))
- }, [])
+ prefetchProjects(client)
+ }, [client])
+}
+
+export function useAutoProjectsPrefetch() {
+ const prefetch = useProjectsPrefetch()
+
+ const called = useRef<boolean>(false)
+ if (called.current === false) {
+ called.current = true
+ prefetch()
+ }
+}
+
+export function invalidateProjectsQuery(client: QueryClient) {
+ return client.invalidateQueries(projectKeys.list())
}
diff --git a/studio/hooks/index.ts b/studio/hooks/index.ts
index 25a3607e163..c8c4d6b4db6 100644
--- a/studio/hooks/index.ts
+++ b/studio/hooks/index.ts
@@ -1,7 +1,9 @@
-export * from './misc/useStore'
-export * from './misc/withAuth'
-export * from './misc/useImmutableValue'
+export * from './deprecated'
export * from './misc/useCheckPermissions'
+export * from './misc/useImmutableValue'
export * from './misc/useLocalStorage'
-export * from './deprecated'
+export * from './misc/useSelectedOrganization'
+export * from './misc/useSelectedProject'
+export * from './misc/useStore'
+export * from './misc/withAuth'
export * from './ui'
diff --git a/studio/hooks/misc/useCheckPermissions.ts b/studio/hooks/misc/useCheckPermissions.ts
index 3866b4295ad..300285def31 100644
--- a/studio/hooks/misc/useCheckPermissions.ts
+++ b/studio/hooks/misc/useCheckPermissions.ts
@@ -1,35 +1,41 @@
-import { useStore } from 'hooks'
import jsonLogic from 'json-logic-js'
+
+import { usePermissionsQuery } from 'data/permissions/permissions-query'
import { IS_PLATFORM } from 'lib/constants'
+import { useSelectedOrganization } from './useSelectedOrganization'
const toRegexpString = (actionOrResource: string) =>
`^${actionOrResource.replace('.', '\\.').replace('%', '.*')}$`
-export function checkPermissions(
+export function useCheckPermissions(
action: string,
resource: string,
data?: object,
organizationId?: number
) {
+ const { data: permissions } = usePermissionsQuery({
+ enabled: IS_PLATFORM,
+ })
+ const organization = useSelectedOrganization()
+
if (!IS_PLATFORM) return true
- const { ui } = useStore()
- const orgId = organizationId ?? ui?.selectedOrganization?.id
+ const orgId = organizationId ?? organization?.id
- return (ui?.permissions ?? [])
+ return (permissions ?? [])
.filter(
- (permission: {
- actions: string[]
- condition: jsonLogic.RulesLogic
- organization_id: number
- resources: string[]
- }) =>
+ (permission) =>
+ permission.organization_id === orgId &&
permission.actions.some((act) => (action ? action.match(toRegexpString(act)) : null)) &&
- permission.resources.some((res) => resource.match(toRegexpString(res))) &&
- permission.organization_id === orgId
+ permission.resources.some((res) => resource.match(toRegexpString(res)))
)
.some(
({ condition }: { condition: jsonLogic.RulesLogic }) =>
condition === null || jsonLogic.apply(condition, { resource_name: resource, ...data })
)
}
+
+/**
+ * @deprecated use useCheckPermissions instead
+ */
+export const checkPermissions = useCheckPermissions
diff --git a/studio/hooks/misc/useSelectedOrganization.ts b/studio/hooks/misc/useSelectedOrganization.ts
new file mode 100644
index 00000000000..b63927fd14b
--- /dev/null
+++ b/studio/hooks/misc/useSelectedOrganization.ts
@@ -0,0 +1,17 @@
+import { useParams } from 'common'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useMemo } from 'react'
+
+import { useSelectedProject } from './useSelectedProject'
+
+export function useSelectedOrganization() {
+ const { slug } = useParams()
+ const { data } = useOrganizationsQuery()
+ const selectedProject = useSelectedProject()
+
+ return useMemo(() => {
+ return data?.find(
+ (org) => org.slug === slug || (selectedProject && org.id === selectedProject.organization_id)
+ )
+ }, [data, selectedProject, slug])
+}
diff --git a/studio/hooks/misc/useSelectedProject.ts b/studio/hooks/misc/useSelectedProject.ts
new file mode 100644
index 00000000000..00c77b5a19e
--- /dev/null
+++ b/studio/hooks/misc/useSelectedProject.ts
@@ -0,0 +1,12 @@
+import { useParams } from 'common'
+import { useProjectsQuery } from 'data/projects/projects-query'
+import { useMemo } from 'react'
+
+export function useSelectedProject() {
+ const { ref } = useParams()
+ const { data } = useProjectsQuery()
+
+ return useMemo(() => {
+ return data?.find((project) => project.ref === ref)
+ }, [data, ref])
+}
diff --git a/studio/hooks/misc/withAuth.tsx b/studio/hooks/misc/withAuth.tsx
index be44628398e..3daa4716f66 100644
--- a/studio/hooks/misc/withAuth.tsx
+++ b/studio/hooks/misc/withAuth.tsx
@@ -2,9 +2,9 @@ import Head from 'next/head'
import { useRouter } from 'next/router'
import { ComponentType, useEffect } from 'react'
+import { useParams } from 'common/hooks'
import { usePermissionsQuery } from 'data/permissions/permissions-query'
import { useStore } from 'hooks'
-import { useParams } from 'common/hooks'
import { useAuth } from 'lib/auth'
import { IS_PLATFORM } from 'lib/constants'
import { getReturnToPath, STORAGE_KEY } from 'lib/gotrue'
@@ -34,17 +34,12 @@ export function withAuth<T>(
const rootStore = useStore()
const { isLoading, session } = useAuth()
- const { app, ui } = rootStore
+ const { ui } = rootStore
const page = router.pathname.split('/').slice(3).join('/')
const redirectTo = options?.redirectTo ?? defaultRedirectTo(ref)
const redirectIfFound = options?.redirectIfFound
- useEffect(() => {
- if (!app.organizations.isInitialized) app.organizations.load()
- if (!app.projects.isInitialized) app.projects.load()
- }, [app.organizations.isInitialized, app.projects.isInitialized])
-
usePermissionsQuery({
enabled: IS_PLATFORM,
onSuccess(permissions) {
diff --git a/studio/lib/auth.tsx b/studio/lib/auth.tsx
index 762cc3da511..d6bef4ea744 100644
--- a/studio/lib/auth.tsx
+++ b/studio/lib/auth.tsx
@@ -1,6 +1,6 @@
import { useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/router'
-import { PropsWithChildren, useCallback, useEffect, useRef } from 'react'
+import { PropsWithChildren, useCallback, useEffect } from 'react'
import {
AuthContext as AuthContextInternal,
@@ -8,17 +8,19 @@ import {
gotrueClient,
useTelemetryProps,
} from 'common'
+import { invalidateOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useProfileCreateMutation } from 'data/profile/profile-create-mutation'
import { useProfileQuery } from 'data/profile/profile-query'
import { useStore } from 'hooks'
import Telemetry from 'lib/telemetry'
import { GOTRUE_ERRORS, IS_PLATFORM } from './constants'
import { clearLocalStorage } from './local-storage'
-import { useProfileCreateMutation } from 'data/profile/profile-create-mutation'
export const AuthContext = AuthContextInternal
export const AuthProvider = ({ children }: PropsWithChildren<{}>) => {
- const { ui, app } = useStore()
+ const queryClient = useQueryClient()
+ const { ui } = useStore()
const router = useRouter()
const telemetryProps = useTelemetryProps()
@@ -56,12 +58,14 @@ export const AuthProvider = ({ children }: PropsWithChildren<{}>) => {
}, [])
const { mutate: createProfile } = useProfileCreateMutation({
- onSuccess() {
+ async onSuccess() {
Telemetry.sendEvent(
{ category: 'conversion', action: 'sign_up', label: '' },
telemetryProps,
router
)
+
+ await invalidateOrganizationsQuery(queryClient)
},
onError(err) {
ui.setNotification({
@@ -75,12 +79,6 @@ export const AuthProvider = ({ children }: PropsWithChildren<{}>) => {
useProfileQuery({
onSuccess(profile) {
Telemetry.sendIdentify(profile, telemetryProps)
-
- // [Joshen] Temp fix: For new users, the GET profile call also creates a default org
- // But because the dashboard's logged in state is using gotrue as the source of truth
- // the home page loads before the GET profile call completes (and consequently before the
- // creation of the default org). Hence why calling org load here
- app.organizations.load()
},
onError(err) {
// if the user does not yet exist, create a profile for them
@@ -104,5 +102,5 @@ export function useSignOut() {
await queryClient.resetQueries()
return result
- }, [])
+ }, [queryClient])
}
diff --git a/studio/pages/new/[slug].tsx b/studio/pages/new/[slug].tsx
index fe03cf0ddc3..38c5c7dbb8f 100644
--- a/studio/pages/new/[slug].tsx
+++ b/studio/pages/new/[slug].tsx
@@ -1,47 +1,48 @@
-import Router, { useRouter } from 'next/router'
-import { useRef, useState, useEffect, PropsWithChildren } from 'react'
-import { debounce, isUndefined, values } from 'lodash'
-import { toJS } from 'mobx'
-import { observer } from 'mobx-react-lite'
-import generator from 'generate-password'
-import { Button, Listbox, IconUsers, Input, Alert, IconHelpCircle, Toggle, IconInfo } from 'ui'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { NextPageWithLayout } from 'types'
-import { passwordStrength, pluckObjectFields } from 'lib/helpers'
+import generator from 'generate-password'
+import { debounce, isUndefined } from 'lodash'
+import { observer } from 'mobx-react-lite'
+import Router, { useRouter } from 'next/router'
+import { useEffect, useRef, useState } from 'react'
+
+import { useParams } from 'common/hooks'
+import SpendCapModal from 'components/interfaces/Billing/SpendCapModal'
+import {
+ EmptyPaymentMethodWarning,
+ FreeProjectLimitWarning,
+ NotOrganizationOwnerWarning,
+} from 'components/interfaces/Organization/NewProject'
+import { WizardLayoutWithoutAuth } from 'components/layouts'
+import DisabledWarningDueToIncident from 'components/ui/DisabledWarningDueToIncident'
+import InformationBox from 'components/ui/InformationBox'
+import Panel from 'components/ui/Panel'
+import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'
+import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useCheckPermissions, useFlag, useStore, withAuth } from 'hooks'
import { get, post } from 'lib/common/fetch'
import {
API_URL,
- PROVIDERS,
+ AWS_REGIONS,
+ CloudProvider,
DEFAULT_MINIMUM_PASSWORD_STRENGTH,
- PRICING_TIER_LABELS,
+ DEFAULT_PROVIDER,
+ FLY_REGIONS,
PRICING_TIER_DEFAULT_KEY,
PRICING_TIER_FREE_KEY,
+ PRICING_TIER_LABELS,
PRICING_TIER_PRODUCT_IDS,
- AWS_REGIONS,
- FLY_REGIONS,
- CloudProvider,
+ PROVIDERS,
Region,
- DEFAULT_PROVIDER,
} from 'lib/constants'
-import { useStore, useFlag, withAuth, checkPermissions } from 'hooks'
-import { useParams } from 'common/hooks'
-import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'
-import { WizardLayoutWithoutAuth } from 'components/layouts'
-import Panel from 'components/ui/Panel'
-import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'
-import DisabledWarningDueToIncident from 'components/ui/DisabledWarningDueToIncident'
-import {
- FreeProjectLimitWarning,
- NotOrganizationOwnerWarning,
- EmptyPaymentMethodWarning,
-} from 'components/interfaces/Organization/NewProject'
-import SpendCapModal from 'components/interfaces/Billing/SpendCapModal'
-import InformationBox from 'components/ui/InformationBox'
+import { passwordStrength, pluckObjectFields } from 'lib/helpers'
+import { NextPageWithLayout } from 'types'
+import { Alert, Button, IconHelpCircle, IconInfo, IconUsers, Input, Listbox, Toggle } from 'ui'
const Wizard: NextPageWithLayout = () => {
const router = useRouter()
const { slug } = useParams()
- const { app, ui } = useStore()
+ const { ui } = useStore()
const projectCreationDisabled = useFlag('disableProjectCreationAndUpdate')
const cloudProviderEnabled = useFlag('enableFlyCloudProvider')
@@ -66,17 +67,17 @@ const Wizard: NextPageWithLayout = () => {
const [isSpendCapEnabled, setIsSpendCapEnabled] = useState(true)
- const organizations = values(toJS(app.organizations.list()))
- const currentOrg = organizations.find((o: any) => o.slug === slug)
+ const { data: organizations, isSuccess: isOrganizationsSuccess } = useOrganizationsQuery()
+ const currentOrg = organizations?.find((o: any) => o.slug === slug)
const billedViaOrg = Boolean(currentOrg?.subscription_id)
const [availableRegions, setAvailableRegions] = useState(
getAvailableRegions(PROVIDERS[cloudProvider].id)
)
- const isAdmin = checkPermissions(PermissionAction.CREATE, 'projects')
+ const isAdmin = useCheckPermissions(PermissionAction.CREATE, 'projects')
const isInvalidSlug = isUndefined(currentOrg)
- const isEmptyOrganizations = organizations.length <= 0 && app.organizations.isInitialized
+ const isEmptyOrganizations = (organizations?.length ?? 0) <= 0 && isOrganizationsSuccess
const isEmptyPaymentMethod = paymentMethods ? !paymentMethods.length : false
const isSelectFreeTier = dbPricingTierKey === PRICING_TIER_FREE_KEY
const hasMembersExceedingFreeTierLimit = (membersExceededLimit || []).length > 0
@@ -108,8 +109,8 @@ const Wizard: NextPageWithLayout = () => {
* Redirect to first org if the slug doesn't match an org slug
* this is mainly to capture the /project/new url, which is redirected from database.new
*/
- if (isInvalidSlug && organizations.length > 0) {
- router.push(`/new/${organizations[0].slug}`)
+ if (isInvalidSlug && (organizations?.length ?? 0) > 0) {
+ router.push(`/new/${organizations?.[0].slug}`)
}
useEffect(() => {
@@ -210,7 +211,6 @@ const Wizard: NextPageWithLayout = () => {
message: `Failed to create new project: ${response.error.message}`,
})
} else {
- app.onProjectCreated(response)
router.push(`/project/${response.ref}/building`)
}
}
@@ -245,7 +245,7 @@ const Wizard: NextPageWithLayout = () => {
return (
<Panel
hideHeaderStyling
- loading={!app.organizations.isInitialized || isLoadingFreeProjectLimitCheck}
+ loading={!isOrganizationsSuccess || isLoadingFreeProjectLimitCheck}
title={
<div key="panel-title">
<h3>Create a new project</h3>
@@ -292,14 +292,14 @@ const Wizard: NextPageWithLayout = () => {
'border-panel-border-interior-light dark:border-panel-border-interior-dark',
].join(' ')}
>
- {organizations.length > 0 && (
+ {(organizations?.length ?? 0) > 0 && (
<Listbox
label="Organization"
layout="horizontal"
value={currentOrg?.slug}
onChange={(slug) => router.push(`/new/${slug}`)}
>
- {organizations.map((x: any) => (
+ {organizations?.map((x: any) => (
<Listbox.Option
key={x.id}
label={x.name}
@@ -565,22 +565,18 @@ const Wizard: NextPageWithLayout = () => {
)
}
-const PageLayout = withAuth(
- observer<PropsWithChildren<{}>>(({ children }) => {
- const router = useRouter()
- const { slug } = router.query
-
- const { app } = useStore()
- const organizations = values(toJS(app.organizations.list()))
- const currentOrg = organizations.find((o: any) => o.slug === slug)
-
- return (
- <WizardLayoutWithoutAuth organization={currentOrg} project={null}>
- {children}
- </WizardLayoutWithoutAuth>
- )
- })
-)
+const PageLayout = withAuth(({ children }) => {
+ const { slug } = useParams()
+
+ const { data: organizations } = useOrganizationsQuery()
+ const currentOrg = organizations?.find((o: any) => o.slug === slug)
+
+ return (
+ <WizardLayoutWithoutAuth organization={currentOrg} project={null}>
+ {children}
+ </WizardLayoutWithoutAuth>
+ )
+})
Wizard.getLayout = (page) => <PageLayout>{page}</PageLayout>
diff --git a/studio/pages/new/index.tsx b/studio/pages/new/index.tsx
index 8ca1dcfd02d..b4e54938c00 100644
--- a/studio/pages/new/index.tsx
+++ b/studio/pages/new/index.tsx
@@ -1,13 +1,15 @@
-import { useState } from 'react'
+import { useQueryClient } from '@tanstack/react-query'
import { observer } from 'mobx-react-lite'
-import { Button, Input, Listbox } from 'ui'
import { useRouter } from 'next/router'
+import { useState } from 'react'
+import { Button, Input, Listbox } from 'ui'
-import { API_URL } from 'lib/constants'
-import { useStore } from 'hooks'
-import { post } from 'lib/common/fetch'
import { WizardLayout } from 'components/layouts'
import Panel from 'components/ui/Panel'
+import { invalidateOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useStore } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
import { NextPageWithLayout } from 'types'
const ORG_KIND_TYPES = {
@@ -33,7 +35,8 @@ const ORG_SIZE_DEFAULT = '1'
* No org selected yet, create a new one
*/
const Wizard: NextPageWithLayout = () => {
- const { ui, app } = useStore()
+ const queryClient = useQueryClient()
+ const { ui } = useStore()
const router = useRouter()
const [orgName, setOrgName] = useState('')
@@ -81,7 +84,7 @@ const Wizard: NextPageWithLayout = () => {
})
} else {
const org = response
- app.onOrgAdded(org)
+ await invalidateOrganizationsQuery(queryClient)
router.push(`/new/${org.slug}`)
}
}
diff --git a/studio/pages/org/[slug]/billing.tsx b/studio/pages/org/[slug]/billing.tsx
index 83c44735b40..774a22c49c0 100644
--- a/studio/pages/org/[slug]/billing.tsx
+++ b/studio/pages/org/[slug]/billing.tsx
@@ -1,30 +1,29 @@
import { useRouter } from 'next/router'
-import { observer } from 'mobx-react-lite'
-import { Tabs } from 'ui'
-import { NextPageWithLayout } from 'types'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import Loading from 'components/ui/Loading'
-import { OrganizationLayout } from 'components/layouts'
import { BillingSettings } from 'components/interfaces/Organization'
+import { OrganizationLayout } from 'components/layouts'
+import Loading from 'components/ui/Loading'
+import { usePermissionsQuery } from 'data/permissions/permissions-query'
+import { useSelectedOrganization } from 'hooks'
+import { NextPageWithLayout } from 'types'
+import { Tabs } from 'ui'
const OrgBillingSettings: NextPageWithLayout = () => {
- const { ui } = useStore()
+ const { data: permissions } = usePermissionsQuery()
+ const selectedOrganization = useSelectedOrganization()
const { slug } = useParams()
const router = useRouter()
return (
<>
- {ui.selectedOrganization === undefined && (ui?.permissions ?? []).length === 0 ? (
+ {selectedOrganization === undefined && (permissions ?? []).length === 0 ? (
<Loading />
) : (
<div className="p-4 pt-0">
<div className="space-y-3">
<section className="mt-4">
- <h1 className="text-3xl">
- {ui.selectedOrganization?.name ?? 'Organization'} settings
- </h1>
+ <h1 className="text-3xl">{selectedOrganization?.name ?? 'Organization'} settings</h1>
</section>
<nav>
<Tabs
@@ -53,4 +52,5 @@ const OrgBillingSettings: NextPageWithLayout = () => {
}
OrgBillingSettings.getLayout = (page) => <OrganizationLayout>{page}</OrganizationLayout>
-export default observer(OrgBillingSettings)
+
+export default OrgBillingSettings
diff --git a/studio/pages/org/[slug]/general.tsx b/studio/pages/org/[slug]/general.tsx
index f07415ba47e..a37e32a78e8 100644
--- a/studio/pages/org/[slug]/general.tsx
+++ b/studio/pages/org/[slug]/general.tsx
@@ -1,30 +1,29 @@
import { useRouter } from 'next/router'
-import { observer } from 'mobx-react-lite'
-import { Tabs } from 'ui'
-import { NextPageWithLayout } from 'types'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import Loading from 'components/ui/Loading'
-import { OrganizationLayout } from 'components/layouts'
import { GeneralSettings } from 'components/interfaces/Organization'
+import { OrganizationLayout } from 'components/layouts'
+import Loading from 'components/ui/Loading'
+import { usePermissionsQuery } from 'data/permissions/permissions-query'
+import { useSelectedOrganization } from 'hooks'
+import { NextPageWithLayout } from 'types'
+import { Tabs } from 'ui'
const OrgGeneralSettings: NextPageWithLayout = () => {
- const { ui } = useStore()
+ const { data: permissions } = usePermissionsQuery()
+ const selectedOrganization = useSelectedOrganization()
const { slug } = useParams()
const router = useRouter()
return (
<>
- {ui.selectedOrganization === undefined && (ui?.permissions ?? []).length === 0 ? (
+ {selectedOrganization === undefined && (permissions ?? []).length === 0 ? (
<Loading />
) : (
<div className="p-4 pt-0">
<div className="space-y-3">
<section className="mt-4">
- <h1 className="text-3xl">
- {ui.selectedOrganization?.name ?? 'Organization'} settings
- </h1>
+ <h1 className="text-3xl">{selectedOrganization?.name ?? 'Organization'} settings</h1>
</section>
<nav>
<Tabs
@@ -53,4 +52,5 @@ const OrgGeneralSettings: NextPageWithLayout = () => {
}
OrgGeneralSettings.getLayout = (page) => <OrganizationLayout>{page}</OrganizationLayout>
-export default observer(OrgGeneralSettings)
+
+export default OrgGeneralSettings
diff --git a/studio/pages/org/[slug]/invoices.tsx b/studio/pages/org/[slug]/invoices.tsx
index 5ccf1ebc825..ad95c46b449 100644
--- a/studio/pages/org/[slug]/invoices.tsx
+++ b/studio/pages/org/[slug]/invoices.tsx
@@ -1,30 +1,30 @@
-import { useRouter } from 'next/router'
import { observer } from 'mobx-react-lite'
+import { useRouter } from 'next/router'
import { Tabs } from 'ui'
-import { NextPageWithLayout } from 'types'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import Loading from 'components/ui/Loading'
-import { OrganizationLayout } from 'components/layouts'
import { InvoicesSettings } from 'components/interfaces/Organization'
+import { OrganizationLayout } from 'components/layouts'
+import Loading from 'components/ui/Loading'
+import { usePermissionsQuery } from 'data/permissions/permissions-query'
+import { useSelectedOrganization } from 'hooks'
+import { NextPageWithLayout } from 'types'
const OrgInvoices: NextPageWithLayout = () => {
- const { ui } = useStore()
+ const { data: permissions } = usePermissionsQuery()
+ const selectedOrganization = useSelectedOrganization()
const { slug } = useParams()
const router = useRouter()
return (
<>
- {ui.selectedOrganization === undefined && (ui?.permissions ?? []).length === 0 ? (
+ {selectedOrganization === undefined && (permissions ?? []).length === 0 ? (
<Loading />
) : (
<div className="p-4 pt-0">
<div className="space-y-3">
<section className="mt-4">
- <h1 className="text-3xl">
- {ui.selectedOrganization?.name ?? 'Organization'} settings
- </h1>
+ <h1 className="text-3xl">{selectedOrganization?.name ?? 'Organization'} settings</h1>
</section>
<nav>
<Tabs
diff --git a/studio/pages/org/[slug]/team.tsx b/studio/pages/org/[slug]/team.tsx
index 7f96623cd61..c3c2200b33a 100644
--- a/studio/pages/org/[slug]/team.tsx
+++ b/studio/pages/org/[slug]/team.tsx
@@ -1,30 +1,29 @@
import { useRouter } from 'next/router'
-import { observer } from 'mobx-react-lite'
-import { Tabs } from 'ui'
-import { NextPageWithLayout } from 'types'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import Loading from 'components/ui/Loading'
-import { OrganizationLayout } from 'components/layouts'
import { TeamSettings } from 'components/interfaces/Organization'
+import { OrganizationLayout } from 'components/layouts'
+import Loading from 'components/ui/Loading'
+import { usePermissionsQuery } from 'data/permissions/permissions-query'
+import { useSelectedOrganization } from 'hooks'
+import { NextPageWithLayout } from 'types'
+import { Tabs } from 'ui'
const OrgTeamSettings: NextPageWithLayout = () => {
- const { ui } = useStore()
+ const { data: permissions } = usePermissionsQuery()
+ const selectedOrganization = useSelectedOrganization()
const { slug } = useParams()
const router = useRouter()
return (
<>
- {ui.selectedOrganization === undefined && (ui?.permissions ?? []).length === 0 ? (
+ {selectedOrganization === undefined && (permissions ?? []).length === 0 ? (
<Loading />
) : (
<div className="p-4 pt-0">
<div className="space-y-3">
<section className="mt-4">
- <h1 className="text-3xl">
- {ui.selectedOrganization?.name ?? 'Organization'} settings
- </h1>
+ <h1 className="text-3xl">{selectedOrganization?.name ?? 'Organization'} settings</h1>
</section>
<nav>
<Tabs
@@ -53,4 +52,5 @@ const OrgTeamSettings: NextPageWithLayout = () => {
}
OrgTeamSettings.getLayout = (page) => <OrganizationLayout>{page}</OrganizationLayout>
-export default observer(OrgTeamSettings)
+
+export default OrgTeamSettings
diff --git a/studio/pages/org/_/[[...routeSlug]].tsx b/studio/pages/org/_/[[...routeSlug]].tsx
index 1e53059a44d..65e036ed037 100644
--- a/studio/pages/org/_/[[...routeSlug]].tsx
+++ b/studio/pages/org/_/[[...routeSlug]].tsx
@@ -1,13 +1,13 @@
+import { NextPage } from 'next'
import Link from 'next/link'
import { useRouter } from 'next/router'
-import { NextPage } from 'next'
-import { observer } from 'mobx-react-lite'
-import { Button, IconPlus } from 'ui'
-import { withAuth, useStore } from 'hooks'
-import { BASE_PATH } from 'lib/constants'
-import CardButton from 'components/ui/CardButton'
import ShimmeringCard from 'components/interfaces/Home/ProjectList/ShimmeringCard'
+import CardButton from 'components/ui/CardButton'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
+import { withAuth } from 'hooks'
+import { BASE_PATH } from 'lib/constants'
+import { Button, IconPlus } from 'ui'
const Header = () => {
return (
@@ -29,12 +29,9 @@ const Header = () => {
}
const GenericOrganizationPage: NextPage = () => {
- const { app } = useStore()
const router = useRouter()
- const { organizations } = app
- const { isLoading } = organizations
- const sortedOrganizations = organizations.list()
+ const { data: organizations, isLoading } = useOrganizationsQuery()
const { routeSlug, ...queryParams } = router.query
const queryString =
Object.keys(queryParams).length > 0
@@ -71,7 +68,7 @@ const GenericOrganizationPage: NextPage = () => {
<ShimmeringCard />
<ShimmeringCard />
</ul>
- ) : sortedOrganizations.length === 0 ? (
+ ) : organizations?.length === 0 ? (
<div className="col-span-4 space-y-4 rounded-lg border-2 border-dashed border-gray-300 p-6 text-center">
<div className="space-y-1">
<p>You are not part of any organizations yet</p>
@@ -94,7 +91,7 @@ const GenericOrganizationPage: NextPage = () => {
'sm:grid-cols-1 md:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3',
].join(' `')}
>
- {sortedOrganizations.map((organization) => (
+ {organizations?.map((organization) => (
<li key={organization.slug} className="col-span-1">
<CardButton
linkHref={urlRewriterFactory(routeSlug)(organization.slug)}
@@ -121,4 +118,4 @@ const GenericOrganizationPage: NextPage = () => {
)
}
-export default withAuth(observer(GenericOrganizationPage))
+export default withAuth(GenericOrganizationPage)
diff --git a/studio/pages/project/[ref]/api/graphiql.tsx b/studio/pages/project/[ref]/api/graphiql.tsx
index 95492f7a2d1..e215c922b63 100644
--- a/studio/pages/project/[ref]/api/graphiql.tsx
+++ b/studio/pages/project/[ref]/api/graphiql.tsx
@@ -1,22 +1,24 @@
-import { useEffect, useMemo } from 'react'
+import { Fetcher, createGraphiQLFetcher } from '@graphiql/toolkit'
import { observer } from 'mobx-react-lite'
-import { createGraphiQLFetcher, Fetcher } from '@graphiql/toolkit'
+import { useEffect, useMemo } from 'react'
-import { NextPageWithLayout } from 'types'
+import { useTheme } from 'common'
import { useParams } from 'common/hooks'
-import { useStore } from 'hooks'
-import { API_URL, IS_PLATFORM } from 'lib/constants'
import ExtensionCard from 'components/interfaces/Database/Extensions/ExtensionCard'
import GraphiQL from 'components/interfaces/GraphQL/GraphiQL'
import { DocsLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import Connecting from 'components/ui/Loading/Loading'
import { useSessionAccessTokenQuery } from 'data/auth/session-access-token-query'
import { useProjectApiQuery } from 'data/config/project-api-query'
-import { useTheme } from 'common'
+import { useStore } from 'hooks'
+import { API_URL, IS_PLATFORM } from 'lib/constants'
+import { NextPageWithLayout } from 'types'
const GraphiQLPage: NextPageWithLayout = () => {
const { ref: projectRef } = useParams()
- const { ui, meta } = useStore()
+ const { meta } = useStore()
+ const { project } = useProjectContext()
const { isDarkMode } = useTheme()
const theme = isDarkMode ? 'dark' : 'light'
@@ -32,12 +34,12 @@ const GraphiQLPage: NextPageWithLayout = () => {
: undefined
useEffect(() => {
- if (ui.selectedProject?.ref) {
+ if (project?.ref) {
// Schemas may be needed when enabling the GraphQL extension
meta.schemas.load()
meta.extensions.load()
}
- }, [ui.selectedProject?.ref])
+ }, [project?.ref])
const graphqlUrl = `${API_URL}/projects/${projectRef}/api/graphql`
diff --git a/studio/pages/project/[ref]/api/index.tsx b/studio/pages/project/[ref]/api/index.tsx
index 64cb1e74796..c193e99317a 100644
--- a/studio/pages/project/[ref]/api/index.tsx
+++ b/studio/pages/project/[ref]/api/index.tsx
@@ -1,16 +1,16 @@
+import { observer, useLocalObservable } from 'mobx-react-lite'
import { useRouter } from 'next/router'
import { FC, createContext, useContext, useEffect, useState } from 'react'
-import { observer, useLocalObservable } from 'mobx-react-lite'
-import { NextPageWithLayout } from 'types'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { snakeToCamel } from 'lib/helpers'
-import { useProjectApiQuery } from 'data/config/project-api-query'
-import { DocsLayout } from 'components/layouts'
import { GeneralContent, ResourceContent, RpcContent } from 'components/interfaces/Docs'
-import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
import LangSelector from 'components/interfaces/Docs/LangSelector'
+import { DocsLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
+import { snakeToCamel } from 'lib/helpers'
+import { NextPageWithLayout } from 'types'
const PageContext = createContext(null)
@@ -45,9 +45,7 @@ const PageConfig: NextPageWithLayout = () => {
const router = useRouter()
const { query } = router
-
- const { ui } = useStore()
- const project = ui.selectedProject
+ const { project } = useProjectContext()
PageState.projectRef = query.ref
return (
diff --git a/studio/pages/project/[ref]/auth/providers.tsx b/studio/pages/project/[ref]/auth/providers.tsx
index 47112f72c8c..b30a17e9dd5 100644
--- a/studio/pages/project/[ref]/auth/providers.tsx
+++ b/studio/pages/project/[ref]/auth/providers.tsx
@@ -1,20 +1,22 @@
-import { useEffect } from 'react'
-import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { observer } from 'mobx-react-lite'
+import { useEffect } from 'react'
-import { NextPageWithLayout } from 'types'
-import { checkPermissions, useStore } from 'hooks'
import { AuthProvidersForm } from 'components/interfaces'
import { AuthLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { FormsContainer } from 'components/ui/Forms'
import NoPermission from 'components/ui/NoPermission'
+import { checkPermissions, useStore } from 'hooks'
+import { NextPageWithLayout } from 'types'
const PageLayout: NextPageWithLayout = () => {
- const { ui, authConfig } = useStore()
+ const { authConfig } = useStore()
+ const { project } = useProjectContext()
useEffect(() => {
authConfig.load()
- }, [ui.selectedProjectRef])
+ }, [project?.ref])
const canReadAuthSettings = checkPermissions(PermissionAction.READ, 'custom_config_gotrue')
diff --git a/studio/pages/project/[ref]/auth/templates.tsx b/studio/pages/project/[ref]/auth/templates.tsx
index 6d4db080b1d..6bb6d7757ed 100644
--- a/studio/pages/project/[ref]/auth/templates.tsx
+++ b/studio/pages/project/[ref]/auth/templates.tsx
@@ -1,20 +1,22 @@
-import { useEffect } from 'react'
-import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { observer } from 'mobx-react-lite'
+import { useEffect } from 'react'
-import { NextPageWithLayout } from 'types'
-import { useStore, checkPermissions } from 'hooks'
-import { AuthLayout } from 'components/layouts'
import { EmailTemplates } from 'components/interfaces'
+import { AuthLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { FormsContainer } from 'components/ui/Forms'
import NoPermission from 'components/ui/NoPermission'
+import { checkPermissions, useStore } from 'hooks'
+import { NextPageWithLayout } from 'types'
const PageLayout: NextPageWithLayout = () => {
- const { ui, authConfig } = useStore()
+ const { authConfig } = useStore()
+ const { project } = useProjectContext()
useEffect(() => {
authConfig.load()
- }, [ui.selectedProjectRef])
+ }, [project?.ref])
const canReadAuthSettings = checkPermissions(PermissionAction.READ, 'custom_config_gotrue')
diff --git a/studio/pages/project/[ref]/auth/url-configuration.tsx b/studio/pages/project/[ref]/auth/url-configuration.tsx
index b0415afb0c9..9a573653d86 100644
--- a/studio/pages/project/[ref]/auth/url-configuration.tsx
+++ b/studio/pages/project/[ref]/auth/url-configuration.tsx
@@ -1,22 +1,23 @@
-import { useEffect } from 'react'
-import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { observer } from 'mobx-react-lite'
+import { useEffect } from 'react'
-import { NextPageWithLayout } from 'types'
-import { useStore, checkPermissions } from 'hooks'
-import { AuthLayout } from 'components/layouts'
-
-import NoPermission from 'components/ui/NoPermission'
import RedirectUrls from 'components/interfaces/Auth/RedirectUrls/RedirectUrls'
-import { FormsContainer } from 'components/ui/Forms'
import SiteUrl from 'components/interfaces/Auth/SiteUrl/SiteUrl'
+import { AuthLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { FormsContainer } from 'components/ui/Forms'
+import NoPermission from 'components/ui/NoPermission'
+import { checkPermissions, useStore } from 'hooks'
+import { NextPageWithLayout } from 'types'
const URLConfiguration: NextPageWithLayout = () => {
- const { ui, authConfig } = useStore()
+ const { authConfig } = useStore()
+ const { project } = useProjectContext()
useEffect(() => {
authConfig.load()
- }, [ui.selectedProjectRef])
+ }, [project?.ref])
const canReadAuthSettings = checkPermissions(PermissionAction.READ, 'custom_config_gotrue')
diff --git a/studio/pages/project/[ref]/auth/users.tsx b/studio/pages/project/[ref]/auth/users.tsx
index 25b4cd71939..f32fc1aa296 100644
--- a/studio/pages/project/[ref]/auth/users.tsx
+++ b/studio/pages/project/[ref]/auth/users.tsx
@@ -10,6 +10,7 @@ import { Users } from 'components/interfaces/Auth'
import { NextPageWithLayout } from 'types'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import NoPermission from 'components/ui/NoPermission'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
export const PageContext = createContext(null)
@@ -81,9 +82,8 @@ const PageLayout = ({ children }: PropsWithChildren<{}>) => {
}
const UsersPage: NextPageWithLayout = () => {
- const { ui } = useStore()
const PageState: any = useContext(PageContext)
- const project: any = ui.selectedProject
+ const { project } = useProjectContext()
useEffect(() => {
PageState!.projectKpsVersion = project?.kpsVersion
diff --git a/studio/pages/project/[ref]/database/backups/pitr.tsx b/studio/pages/project/[ref]/database/backups/pitr.tsx
index 16b78736f2a..09f9941e951 100644
--- a/studio/pages/project/[ref]/database/backups/pitr.tsx
+++ b/studio/pages/project/[ref]/database/backups/pitr.tsx
@@ -1,23 +1,24 @@
-import { useRouter } from 'next/router'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import clsx from 'clsx'
import { observer } from 'mobx-react-lite'
+import { useRouter } from 'next/router'
import { Tabs } from 'ui'
-import clsx from 'clsx'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { NextPageWithLayout } from 'types'
-import { useStore, checkPermissions } from 'hooks'
+import BackupsError from 'components/interfaces/Database/Backups/BackupsError'
+import { PITRNotice, PITRSelection } from 'components/interfaces/Database/Backups/PITR'
import { DatabaseLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import Loading from 'components/ui/Loading'
import NoPermission from 'components/ui/NoPermission'
import UpgradeToPro from 'components/ui/UpgradeToPro'
-import { PITRNotice, PITRSelection } from 'components/interfaces/Database/Backups/PITR'
-import BackupsError from 'components/interfaces/Database/Backups/BackupsError'
+import { checkPermissions, useStore } from 'hooks'
import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
+import { NextPageWithLayout } from 'types'
const DatabasePhysicalBackups: NextPageWithLayout = () => {
- const { ui } = useStore()
const router = useRouter()
- const ref = ui.selectedProject?.ref ?? 'default'
+ const { project } = useProjectContext()
+ const ref = project?.ref ?? 'default'
return (
<div
@@ -53,12 +54,13 @@ DatabasePhysicalBackups.getLayout = (page) => (
<DatabaseLayout title="Database">{page}</DatabaseLayout>
)
-const PITR = () => {
- const { ui, backups } = useStore()
+const PITR = observer(() => {
+ const { backups } = useStore()
+ const { project } = useProjectContext()
const { configuration, error, isLoading } = backups
- const ref = ui.selectedProject?.ref ?? 'default'
- const tier = ui.selectedProject?.subscription_tier
+ const ref = project?.ref ?? 'default'
+ const tier = project?.subscription_tier
const isEnabled = configuration.walg_enabled
const canReadPhysicalBackups = checkPermissions(PermissionAction.READ, 'physical_backups')
@@ -86,6 +88,6 @@ const PITR = () => {
<PITRSelection />
</>
)
-}
+})
-export default observer(DatabasePhysicalBackups)
+export default DatabasePhysicalBackups
diff --git a/studio/pages/project/[ref]/database/backups/scheduled.tsx b/studio/pages/project/[ref]/database/backups/scheduled.tsx
index 1f5b875cbc7..c66b74ee84a 100644
--- a/studio/pages/project/[ref]/database/backups/scheduled.tsx
+++ b/studio/pages/project/[ref]/database/backups/scheduled.tsx
@@ -1,20 +1,22 @@
-import { useRouter } from 'next/router'
-import { observer } from 'mobx-react-lite'
-import { IconInfo, Tabs } from 'ui'
-import clsx from 'clsx'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import clsx from 'clsx'
+import { observer } from 'mobx-react-lite'
+import { useRouter } from 'next/router'
-import { NextPageWithLayout } from 'types'
-import { checkPermissions, useStore } from 'hooks'
-import { DatabaseLayout } from 'components/layouts'
import { BackupsList } from 'components/interfaces/Database'
-import NoPermission from 'components/ui/NoPermission'
+import { DatabaseLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import InformationBox from 'components/ui/InformationBox'
+import NoPermission from 'components/ui/NoPermission'
+import { checkPermissions, useStore } from 'hooks'
+import { NextPageWithLayout } from 'types'
+import { IconInfo, Tabs } from 'ui'
const DatabaseScheduledBackups: NextPageWithLayout = () => {
- const { ui, backups } = useStore()
const router = useRouter()
- const ref = ui.selectedProject?.ref
+ const { backups } = useStore()
+ const { project } = useProjectContext()
+ const ref = project?.ref
const isPitrEnabled = backups?.configuration?.walg_enabled
diff --git a/studio/pages/project/[ref]/database/functions.tsx b/studio/pages/project/[ref]/database/functions.tsx
index 5717e14bbcf..61a262fbeef 100644
--- a/studio/pages/project/[ref]/database/functions.tsx
+++ b/studio/pages/project/[ref]/database/functions.tsx
@@ -1,16 +1,18 @@
-import { useState, useEffect } from 'react'
-import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { observer } from 'mobx-react-lite'
+import { useEffect, useState } from 'react'
-import { useStore, checkPermissions } from 'hooks'
-import { DatabaseLayout } from 'components/layouts'
import { CreateFunction, DeleteFunction } from 'components/interfaces/Database'
-import { NextPageWithLayout } from 'types'
-import NoPermission from 'components/ui/NoPermission'
import FunctionsList from 'components/interfaces/Database/Functions/FunctionsList/FunctionsList'
+import { DatabaseLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import NoPermission from 'components/ui/NoPermission'
+import { checkPermissions, useStore } from 'hooks'
+import { NextPageWithLayout } from 'types'
const FunctionsPage: NextPageWithLayout = () => {
- const { meta, ui } = useStore()
+ const { meta } = useStore()
+ const { project } = useProjectContext()
const [selectedFunction, setSelectedFunction] = useState<any>()
const [showCreateFunctionForm, setShowCreateFunctionForm] = useState<boolean>(false)
const [showDeleteFunctionForm, setShowDeleteFunctionForm] = useState<boolean>(false)
@@ -18,10 +20,10 @@ const FunctionsPage: NextPageWithLayout = () => {
const canReadFunctions = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'functions')
useEffect(() => {
- if (ui.selectedProject?.ref) {
+ if (project?.ref) {
fetchFunctions()
}
- }, [ui.selectedProject?.ref])
+ }, [project?.ref])
const fetchFunctions = async () => {
meta.functions.load()
diff --git a/studio/pages/project/[ref]/database/hooks/index.tsx b/studio/pages/project/[ref]/database/hooks/index.tsx
index 4981cae2e65..d6b062d0cdc 100644
--- a/studio/pages/project/[ref]/database/hooks/index.tsx
+++ b/studio/pages/project/[ref]/database/hooks/index.tsx
@@ -1,26 +1,27 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import clsx from 'clsx'
-import { IconLoader } from 'ui'
-import { useEffect, useState } from 'react'
-import { useRouter } from 'next/router'
import { observer } from 'mobx-react-lite'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useEffect, useState } from 'react'
-import { NextPageWithLayout } from 'types'
-import { checkPermissions, useStore } from 'hooks'
-import { API_URL } from 'lib/constants'
-import { post } from 'lib/common/fetch'
-import { DatabaseLayout } from 'components/layouts'
-import NoPermission from 'components/ui/NoPermission'
-import HooksList from 'components/interfaces/Database/Hooks/HooksList/HooksList'
+import { useParams } from 'common'
import DeleteHookModal from 'components/interfaces/Database/Hooks/DeleteHookModal'
import EditHookPanel from 'components/interfaces/Database/Hooks/EditHookPanel'
+import HooksList from 'components/interfaces/Database/Hooks/HooksList/HooksList'
+import { DatabaseLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
+import NoPermission from 'components/ui/NoPermission'
+import { checkPermissions, useStore } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { NextPageWithLayout } from 'types'
+import { IconLoader } from 'ui'
const HooksPage: NextPageWithLayout = () => {
const { meta, ui } = useStore()
+ const { project } = useProjectContext()
- const router = useRouter()
- const { ref } = router.query
+ const { ref } = useParams()
const schemas = meta.schemas.list()
const { isLoading: isLoadingSchemas } = meta.schemas
@@ -33,8 +34,8 @@ const HooksPage: NextPageWithLayout = () => {
const canCreateWebhooks = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'triggers')
useEffect(() => {
- if (ui.selectedProject?.ref) meta.hooks.load()
- }, [ui.selectedProject?.ref])
+ if (project?.ref) meta.hooks.load()
+ }, [project?.ref])
const enableHooksForProject = async () => {
const res = await post(`${API_URL}/database/${ref}/hook-enable`, {})
diff --git a/studio/pages/project/[ref]/database/tables.tsx b/studio/pages/project/[ref]/database/tables.tsx
index 74bfaa45637..16e49895958 100644
--- a/studio/pages/project/[ref]/database/tables.tsx
+++ b/studio/pages/project/[ref]/database/tables.tsx
@@ -1,23 +1,21 @@
+import type { PostgresColumn, PostgresTable } from '@supabase/postgres-meta'
import { useQueryClient } from '@tanstack/react-query'
-import { useState, useEffect } from 'react'
-import { observer } from 'mobx-react-lite'
import { isUndefined } from 'lodash'
-import type { PostgresColumn, PostgresTable } from '@supabase/postgres-meta'
-import { Modal } from 'ui'
-
-import { useStore } from 'hooks'
-import { sqlKeys } from 'data/sql/keys'
+import { observer } from 'mobx-react-lite'
+import { useEffect, useState } from 'react'
-import { DatabaseLayout } from 'components/layouts'
-import ConfirmationModal from 'components/ui/ConfirmationModal'
-import { TableList, ColumnList } from 'components/interfaces/Database'
+import { ColumnList, TableList } from 'components/interfaces/Database'
import { SidePanelEditor } from 'components/interfaces/TableGridEditor'
+import { DatabaseLayout } from 'components/layouts'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import ConfirmationModal from 'components/ui/ConfirmationModal'
+import { sqlKeys } from 'data/sql/keys'
+import { useStore } from 'hooks'
import { NextPageWithLayout } from 'types'
+import { Modal } from 'ui'
const DatabaseTables: NextPageWithLayout = () => {
const { meta, ui } = useStore()
-
const { project } = useProjectContext()
const queryClient = useQueryClient()
@@ -34,10 +32,10 @@ const DatabaseTables: NextPageWithLayout = () => {
const [selectedTableToDelete, setSelectedTableToDelete] = useState<PostgresTable>()
useEffect(() => {
- if (ui.selectedProject?.ref) {
+ if (project?.ref) {
meta.types.load()
}
- }, [ui.selectedProject?.ref])
+ }, [project?.ref])
const onAddTable = () => {
setSidePanelKey('table')
diff --git a/studio/pages/project/[ref]/database/triggers.tsx b/studio/pages/project/[ref]/database/triggers.tsx
index f8d61449fa3..a44389ce33e 100644
--- a/studio/pages/project/[ref]/database/triggers.tsx
+++ b/studio/pages/project/[ref]/database/triggers.tsx
@@ -1,16 +1,18 @@
-import { useEffect, useState } from 'react'
-import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { observer } from 'mobx-react-lite'
+import { useEffect, useState } from 'react'
-import { NextPageWithLayout } from 'types'
-import { checkPermissions, useStore } from 'hooks'
-import { DatabaseLayout } from 'components/layouts'
import { CreateTrigger, DeleteTrigger } from 'components/interfaces/Database'
import TriggersList from 'components/interfaces/Database/Triggers/TriggersList/TriggersList'
+import { DatabaseLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import NoPermission from 'components/ui/NoPermission'
+import { checkPermissions, useStore } from 'hooks'
+import { NextPageWithLayout } from 'types'
const TriggersPage: NextPageWithLayout = () => {
- const { meta, ui } = useStore()
+ const { meta } = useStore()
+ const { project } = useProjectContext()
const [filterString, setFilterString] = useState<string>('')
const [selectedTrigger, setSelectedTrigger] = useState<any>()
@@ -20,10 +22,10 @@ const TriggersPage: NextPageWithLayout = () => {
const canReadTriggers = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'triggers')
useEffect(() => {
- if (ui.selectedProject?.ref) {
+ if (project?.ref) {
fetchTriggers()
}
- }, [ui.selectedProject?.ref])
+ }, [project?.ref])
const fetchTriggers = async () => {
meta.triggers.load()
diff --git a/studio/pages/project/[ref]/editor/index.tsx b/studio/pages/project/[ref]/editor/index.tsx
index 23384fd610d..6cb80edcfdb 100644
--- a/studio/pages/project/[ref]/editor/index.tsx
+++ b/studio/pages/project/[ref]/editor/index.tsx
@@ -1,20 +1,25 @@
-import { useState } from 'react'
-import router from 'next/router'
-import { observer } from 'mobx-react-lite'
-import { isUndefined } from 'lodash'
import type { PostgresTable } from '@supabase/postgres-meta'
+import { isUndefined } from 'lodash'
+import { observer } from 'mobx-react-lite'
+import router from 'next/router'
+import { useState } from 'react'
-import { NextPageWithLayout } from 'types'
-import { useStore, withAuth } from 'hooks'
-import { Entity } from 'data/entity-types/entity-type-query'
-import { TableEditorLayout } from 'components/layouts'
import { EmptyState, SidePanelEditor } from 'components/interfaces/TableGridEditor'
+import { TableEditorLayout } from 'components/layouts'
+import {
+ ProjectContextFromParamsProvider,
+ useProjectContext,
+} from 'components/layouts/ProjectLayout/ProjectContext'
import ConfirmationModal from 'components/ui/ConfirmationModal'
-import { ProjectContextFromParamsProvider } from 'components/layouts/ProjectLayout/ProjectContext'
+import { Entity } from 'data/entity-types/entity-type-query'
+import { useStore, withAuth } from 'hooks'
+import { NextPageWithLayout } from 'types'
const TableEditorPage: NextPageWithLayout = () => {
const { meta, ui } = useStore()
- const projectRef = ui.selectedProject?.ref
+ const { project } = useProjectContext()
+ const projectRef = project?.ref
+
const [sidePanelKey, setSidePanelKey] = useState<'row' | 'column' | 'table'>()
const [isDeleting, setIsDeleting] = useState<boolean>(false)
const [isDuplicating, setIsDuplicating] = useState<boolean>(false)
diff --git a/studio/pages/project/[ref]/index.tsx b/studio/pages/project/[ref]/index.tsx
index af738885e0d..f380381c48c 100644
--- a/studio/pages/project/[ref]/index.tsx
+++ b/studio/pages/project/[ref]/index.tsx
@@ -1,23 +1,16 @@
-import { observer } from 'mobx-react-lite'
-
-import { useStore } from 'hooks'
-import { useParams } from 'common/hooks'
-import { NextPageWithLayout } from 'types'
-import { IS_PLATFORM, PROJECT_STATUS } from 'lib/constants'
-import { ProjectLayoutWithAuth } from 'components/layouts'
-import { ExampleProject, ClientLibrary } from 'components/interfaces/Home'
+import { ClientLibrary, ExampleProject } from 'components/interfaces/Home'
import { CLIENT_LIBRARIES, EXAMPLE_PROJECTS } from 'components/interfaces/Home/Home.constants'
import ProjectUsageSection from 'components/interfaces/Home/ProjectUsageSection'
+import { ProjectLayoutWithAuth } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import ProjectPausedState from 'components/layouts/ProjectLayout/ProjectPausedState'
-import OveragesBanner from 'components/ui/OveragesBanner/OveragesBanner'
import ProjectUpgradeFailedBanner from 'components/ui/ProjectUpgradeFailedBanner'
+import { IS_PLATFORM, PROJECT_STATUS } from 'lib/constants'
+import { NextPageWithLayout } from 'types'
const Home: NextPageWithLayout = () => {
- const { ui } = useStore()
- const { ref } = useParams()
-
- const project = ui.selectedProject
- const projectTier = ui.selectedProject?.subscription_tier
+ const { project } = useProjectContext()
+ const projectTier = project?.subscription_tier
const projectName =
project?.ref !== 'default' && project?.name !== undefined
@@ -78,4 +71,4 @@ Home.getLayout = (page) => (
</ProjectLayoutWithAuth>
)
-export default observer(Home)
+export default Home
diff --git a/studio/pages/project/[ref]/logs/auth-logs.tsx b/studio/pages/project/[ref]/logs/auth-logs.tsx
index 8dc6e5d9765..de0f83e1d43 100644
--- a/studio/pages/project/[ref]/logs/auth-logs.tsx
+++ b/studio/pages/project/[ref]/logs/auth-logs.tsx
@@ -1,17 +1,16 @@
-import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { NextPageWithLayout } from 'types'
-import { checkPermissions, useStore } from 'hooks'
-import { LogsLayout } from 'components/layouts'
import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'
+import { LogsLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import NoPermission from 'components/ui/NoPermission'
+import { useCheckPermissions } from 'hooks'
+import { NextPageWithLayout } from 'types'
const LogsPage: NextPageWithLayout = () => {
- const { ui } = useStore()
- const project = ui.selectedProject
+ const { project } = useProjectContext()
- const canReadAuthLogs = checkPermissions(PermissionAction.ANALYTICS_READ, 'logflare')
+ const canReadAuthLogs = useCheckPermissions(PermissionAction.ANALYTICS_READ, 'logflare')
return !canReadAuthLogs ? (
<NoPermission isFullPage resourceText="access your project's authentication logs" />
@@ -22,4 +21,4 @@ const LogsPage: NextPageWithLayout = () => {
LogsPage.getLayout = (page) => <LogsLayout title="Auth Logs">{page}</LogsLayout>
-export default observer(LogsPage)
+export default LogsPage
diff --git a/studio/pages/project/[ref]/logs/explorer/recent.tsx b/studio/pages/project/[ref]/logs/explorer/recent.tsx
index 0f8bbbe5089..72917678f32 100644
--- a/studio/pages/project/[ref]/logs/explorer/recent.tsx
+++ b/studio/pages/project/[ref]/logs/explorer/recent.tsx
@@ -1,23 +1,23 @@
-import { useEffect } from 'react'
-import Link from 'next/link'
import { observer } from 'mobx-react-lite'
-import { Button, IconClock } from 'ui'
-import { useStore } from 'hooks'
+import Link from 'next/link'
+import { useEffect } from 'react'
+
+import { useParams } from 'common'
import RecentQueriesItem from 'components/interfaces/Settings/Logs/RecentQueriesItem'
import LogsLayout from 'components/layouts/LogsLayout/LogsLayout'
import Table from 'components/to-be-cleaned/Table'
-import { useRouter } from 'next/router'
-import { LogSqlSnippets, NextPageWithLayout } from 'types'
import LogsExplorerHeader from 'components/ui/Logs/LogsExplorerHeader'
+import { useStore } from 'hooks'
+import { LogSqlSnippets, NextPageWithLayout } from 'types'
+import { Button, IconClock } from 'ui'
export const LogsSavedPage: NextPageWithLayout = () => {
- const { content, ui } = useStore()
- const router = useRouter()
- const { ref } = router.query
+ const { content } = useStore()
+ const { ref } = useParams()
useEffect(() => {
content.loadPersistentData()
- }, [ui.selectedProjectRef])
+ }, [ref])
const recent = content.recentLogSqlSnippets.slice().reverse()
return (
diff --git a/studio/pages/project/[ref]/logs/explorer/saved.tsx b/studio/pages/project/[ref]/logs/explorer/saved.tsx
index eebeafa3e6a..b327cec4755 100644
--- a/studio/pages/project/[ref]/logs/explorer/saved.tsx
+++ b/studio/pages/project/[ref]/logs/explorer/saved.tsx
@@ -1,24 +1,23 @@
-import React, { useEffect } from 'react'
-import Link from 'next/link'
import { observer } from 'mobx-react-lite'
-import { IconSave, Loading } from 'ui'
-import { useStore } from 'hooks'
+import Link from 'next/link'
+import { useEffect } from 'react'
+
+import { useParams } from 'common'
import { LogsSavedQueriesItem } from 'components/interfaces/Settings/Logs'
import { LogsLayout } from 'components/layouts'
-
import Table from 'components/to-be-cleaned/Table'
-import { useRouter } from 'next/router'
-import { NextPageWithLayout } from 'types'
import LogsExplorerHeader from 'components/ui/Logs/LogsExplorerHeader'
+import { useStore } from 'hooks'
+import { NextPageWithLayout } from 'types'
+import { IconSave, Loading } from 'ui'
export const LogsSavedPage: NextPageWithLayout = () => {
- const { content, ui } = useStore()
- const router = useRouter()
- const { ref } = router.query
+ const { content } = useStore()
+ const { ref } = useParams()
useEffect(() => {
content.load()
- }, [ui.selectedProject])
+ }, [ref])
if (content.isLoading) {
return <Loading active={true}>{null}</Loading>
diff --git a/studio/pages/project/[ref]/reports/database.tsx b/studio/pages/project/[ref]/reports/database.tsx
index 707cbcad33c..cc165f1c149 100644
--- a/studio/pages/project/[ref]/reports/database.tsx
+++ b/studio/pages/project/[ref]/reports/database.tsx
@@ -1,10 +1,9 @@
import dayjs from 'dayjs'
import { observer } from 'mobx-react-lite'
-import { FC, useEffect, useState } from 'react'
-import { Badge, Button, IconArrowRight, IconExternalLink } from 'ui'
+import { useEffect, useState } from 'react'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
+import { useStore } from 'hooks'
import {
PRICING_TIER_PRODUCT_IDS,
TIME_PERIODS_INFRA,
@@ -12,8 +11,10 @@ import {
} from 'lib/constants'
import { formatBytes } from 'lib/helpers'
import { NextPageWithLayout } from 'types'
+import { Badge, Button, IconArrowRight, IconExternalLink } from 'ui'
import { ReportsLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'
import DateRangePicker from 'components/to-be-cleaned/DateRangePicker'
import Panel from 'components/ui/Panel'
@@ -21,14 +22,11 @@ import SparkBar from 'components/ui/SparkBar'
import { useProjectUsageQuery } from 'data/usage/project-usage-query'
const DatabaseReport: NextPageWithLayout = () => {
- const { ui } = useStore()
- const project = ui.selectedProject
-
return (
<div className="1xl:px-28 mx-auto flex flex-col gap-4 px-5 py-6 lg:px-16 xl:px-24 2xl:px-32">
<div className="content h-full w-full overflow-y-auto">
<div className="w-full">
- <DatabaseUsage project={project} />
+ <DatabaseUsage />
</div>
</div>
</div>
@@ -37,10 +35,11 @@ const DatabaseReport: NextPageWithLayout = () => {
DatabaseReport.getLayout = (page) => <ReportsLayout title="Database">{page}</ReportsLayout>
-export default observer(DatabaseReport)
+export default DatabaseReport
-const DatabaseUsage: FC<any> = () => {
+const DatabaseUsage = observer(() => {
const { meta, ui } = useStore()
+ const { project } = useProjectContext()
const [databaseSize, setDatabaseSize] = useState<any>(0)
const [dateRange, setDateRange] = useState<any>(undefined)
@@ -76,7 +75,7 @@ const DatabaseUsage: FC<any> = () => {
const egressIsApproaching = databaseSizeUsageRatio >= USAGE_APPROACHING_THRESHOLD
const egressIsExceeded = databaseSizeUsageRatio >= 1
- const subscriptionTier = ui.selectedProject?.subscription_tier
+ const subscriptionTier = project?.subscription_tier
const isPaidTier = subscriptionTier !== PRICING_TIER_PRODUCT_IDS.FREE
@@ -221,4 +220,4 @@ const DatabaseUsage: FC<any> = () => {
</div>
</>
)
-}
+})
diff --git a/studio/pages/project/[ref]/reports/index.tsx b/studio/pages/project/[ref]/reports/index.tsx
index 40c56009800..7281b26a1c3 100644
--- a/studio/pages/project/[ref]/reports/index.tsx
+++ b/studio/pages/project/[ref]/reports/index.tsx
@@ -1,19 +1,19 @@
-import { useEffect, useState } from 'react'
-import { observer } from 'mobx-react-lite'
-import { useRouter } from 'next/router'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useRouter } from 'next/router'
+import { useEffect, useState } from 'react'
-import { NextPageWithLayout } from 'types'
-import { checkPermissions, useFlag, useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { post } from 'lib/common/fetch'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
-import { useProjectContentStore } from 'stores/projectContentStore'
-import Loading from 'components/ui/Loading'
+import { ReportsLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
import { createReport } from 'components/to-be-cleaned/Reports/Reports.utils'
-import { ReportsLayout } from 'components/layouts'
+import Loading from 'components/ui/Loading'
import { useProfileQuery } from 'data/profile/profile-query'
+import { checkPermissions, useFlag, useStore } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL, PROJECT_STATUS } from 'lib/constants'
+import { useProjectContentStore } from 'stores/projectContentStore'
+import { NextPageWithLayout } from 'types'
export const UserReportPage: NextPageWithLayout = () => {
const [loading, setLoading] = useState(true)
@@ -23,7 +23,7 @@ export const UserReportPage: NextPageWithLayout = () => {
const { data: profile } = useProfileQuery()
const { ui } = useStore()
- const project = ui.selectedProject
+ const { project } = useProjectContext()
const contentStore = useProjectContentStore(ref)
const canCreateReport = checkPermissions(PermissionAction.CREATE, 'user_content', {
@@ -88,4 +88,4 @@ export const UserReportPage: NextPageWithLayout = () => {
UserReportPage.getLayout = (page) => <ReportsLayout>{page}</ReportsLayout>
-export default observer(UserReportPage)
+export default UserReportPage
diff --git a/studio/pages/project/[ref]/settings/api.tsx b/studio/pages/project/[ref]/settings/api.tsx
index 6bb7f9064ec..258cf74a294 100644
--- a/studio/pages/project/[ref]/settings/api.tsx
+++ b/studio/pages/project/[ref]/settings/api.tsx
@@ -1,20 +1,23 @@
-import { createContext, useEffect } from 'react'
import { observer, useLocalObservable } from 'mobx-react-lite'
+import { createContext, useEffect } from 'react'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { NextPageWithLayout } from 'types'
-import { SettingsLayout } from 'components/layouts'
import ServiceList from 'components/interfaces/Settings/API/ServiceList'
+import { SettingsLayout } from 'components/layouts'
+import {
+ useIsProjectActive,
+ useProjectContext,
+} from 'components/layouts/ProjectLayout/ProjectContext'
+import { useStore } from 'hooks'
+import { NextPageWithLayout } from 'types'
import { IconAlertCircle } from 'ui'
-import { useIsProjectActive } from 'components/layouts/ProjectLayout/ProjectContext'
export const PageContext: any = createContext(null)
const ApiSettings: NextPageWithLayout = () => {
const { ref } = useParams()
- const { meta, ui } = useStore()
- const project = ui.selectedProject
+ const { meta } = useStore()
+ const { project } = useProjectContext()
const isActive = useIsProjectActive()
// [Joshen] Will need to deprecate this
diff --git a/studio/pages/project/[ref]/settings/auth.tsx b/studio/pages/project/[ref]/settings/auth.tsx
index cd090a2af79..acd4f3a940b 100644
--- a/studio/pages/project/[ref]/settings/auth.tsx
+++ b/studio/pages/project/[ref]/settings/auth.tsx
@@ -1,19 +1,21 @@
-import { useEffect } from 'react'
-import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { observer } from 'mobx-react-lite'
+import { useEffect } from 'react'
-import { NextPageWithLayout } from 'types'
-import { checkPermissions, useStore } from 'hooks'
+import { useParams } from 'common'
+import { AutoSchemaForm, SmtpForm } from 'components/interfaces/Auth'
import { SettingsLayout } from 'components/layouts'
import NoPermission from 'components/ui/NoPermission'
-import { SmtpForm, AutoSchemaForm } from 'components/interfaces/Auth'
+import { checkPermissions, useStore } from 'hooks'
+import { NextPageWithLayout } from 'types'
const PageLayout: NextPageWithLayout = () => {
- const { ui, authConfig } = useStore()
+ const { authConfig } = useStore()
+ const { ref: projectRef } = useParams()
useEffect(() => {
authConfig.load()
- }, [ui.selectedProjectRef])
+ }, [projectRef])
const canReadAuthSettings = checkPermissions(PermissionAction.READ, 'custom_config_gotrue')
diff --git a/studio/pages/project/[ref]/settings/billing/invoices.tsx b/studio/pages/project/[ref]/settings/billing/invoices.tsx
index eab1762fe97..491af3ac6ae 100644
--- a/studio/pages/project/[ref]/settings/billing/invoices.tsx
+++ b/studio/pages/project/[ref]/settings/billing/invoices.tsx
@@ -1,21 +1,16 @@
-import { observer } from 'mobx-react-lite'
-import { FC } from 'react'
-
-import { SettingsLayout } from 'components/layouts'
-import { useStore } from 'hooks'
-import { NextPageWithLayout, Project } from 'types'
+import Link from 'next/link'
import { Invoices } from 'components/interfaces/Billing'
-import Link from 'next/link'
+import { SettingsLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useSelectedOrganization } from 'hooks'
+import { NextPageWithLayout } from 'types'
const ProjectBilling: NextPageWithLayout = () => {
- const { ui } = useStore()
- const project = ui.selectedProject
-
return (
<div className="w-full h-full overflow-y-auto content">
<div className="w-full mx-auto">
- <Settings project={project} />
+ <Settings />
</div>
</div>
)
@@ -25,15 +20,12 @@ ProjectBilling.getLayout = (page) => (
<SettingsLayout title="Billing and Usage">{page}</SettingsLayout>
)
-export default observer(ProjectBilling)
-
-interface SettingsProps {
- project?: Project
-}
+export default ProjectBilling
-const Settings: FC<SettingsProps> = ({ project }) => {
- const { ui } = useStore()
- const orgSlug = ui.selectedOrganization?.slug ?? ''
+const Settings = () => {
+ const selectedOrganization = useSelectedOrganization()
+ const { project: selectedProject } = useProjectContext()
+ const orgSlug = selectedOrganization?.slug ?? ''
return (
<div className="container max-w-4xl p-4 space-y-8">
@@ -52,7 +44,7 @@ const Settings: FC<SettingsProps> = ({ project }) => {
</Link>
</div>
- <Invoices projectRef={ui.selectedProject?.ref ?? ''} />
+ <Invoices projectRef={selectedProject?.ref ?? ''} />
</div>
</div>
)
diff --git a/studio/pages/project/[ref]/settings/storage.tsx b/studio/pages/project/[ref]/settings/storage.tsx
index 0ac1df2ea45..8a5bfe475f5 100644
--- a/studio/pages/project/[ref]/settings/storage.tsx
+++ b/studio/pages/project/[ref]/settings/storage.tsx
@@ -1,12 +1,12 @@
-import React, { useEffect } from 'react'
-import { observer } from 'mobx-react-lite'
+import { useEffect } from 'react'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
-import { useFlag, useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { post } from 'lib/common/fetch'
import { SettingsLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { StorageSettings } from 'components/to-be-cleaned/Storage'
+import { useFlag } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL, PROJECT_STATUS } from 'lib/constants'
import { NextPageWithLayout } from 'types'
/**
@@ -14,9 +14,7 @@ import { NextPageWithLayout } from 'types'
*/
const PageLayout: NextPageWithLayout = () => {
const { ref: projectRef } = useParams()
-
- const { ui } = useStore()
- const project = ui.selectedProject
+ const { project } = useProjectContext()
const kpsEnabled = useFlag('initWithKps')
@@ -37,4 +35,4 @@ const PageLayout: NextPageWithLayout = () => {
PageLayout.getLayout = (page) => <SettingsLayout title="Settings">{page}</SettingsLayout>
-export default observer(PageLayout)
+export default PageLayout
diff --git a/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx b/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx
index 1486d50d11a..87078dbacab 100644
--- a/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx
+++ b/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx
@@ -1,15 +1,14 @@
-import React, { useEffect } from 'react'
-import { useRouter } from 'next/router'
-import { observer } from 'mobx-react-lite'
import { find } from 'lodash'
+import { observer } from 'mobx-react-lite'
+import { useEffect } from 'react'
-import { API_URL } from 'lib/constants'
-import { useFlag, useStore } from 'hooks'
-import { post } from 'lib/common/fetch'
-import { PROJECT_STATUS } from 'lib/constants'
+import { useParams } from 'common'
import { StorageLayout } from 'components/layouts'
-import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { StorageExplorer } from 'components/to-be-cleaned/Storage'
+import { useFlag } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL, PROJECT_STATUS } from 'lib/constants'
import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
import { NextPageWithLayout } from 'types'
@@ -17,11 +16,8 @@ import { NextPageWithLayout } from 'types'
* PageLayout is used to setup layout - as usual it will requires inject global store
*/
const PageLayout: NextPageWithLayout = () => {
- const router = useRouter()
- const { ref, bucketId } = router.query
-
- const { ui } = useStore()
- const project = ui.selectedProject
+ const { ref, bucketId } = useParams()
+ const { project } = useProjectContext()
const storageStore = useStorageStore()
const { buckets, loaded } = storageStore
diff --git a/studio/pages/project/[ref]/storage/buckets/index.tsx b/studio/pages/project/[ref]/storage/buckets/index.tsx
index 9b9cdef63f9..875857294ac 100644
--- a/studio/pages/project/[ref]/storage/buckets/index.tsx
+++ b/studio/pages/project/[ref]/storage/buckets/index.tsx
@@ -1,22 +1,20 @@
-import React, { useEffect } from 'react'
-import { observer } from 'mobx-react-lite'
+import { useEffect } from 'react'
-import { API_URL } from 'lib/constants'
-import { useFlag, useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import { post } from 'lib/common/fetch'
-import { PROJECT_STATUS } from 'lib/constants'
import { StorageLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
+import { useFlag } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL, PROJECT_STATUS } from 'lib/constants'
import { NextPageWithLayout } from 'types'
/**
* PageLayout is used to setup layout - as usual it will requires inject global store
*/
-const PageLayout: NextPageWithLayout = ({}) => {
+const PageLayout: NextPageWithLayout = () => {
const { ref } = useParams()
- const { ui } = useStore()
- const project = ui.selectedProject
+ const { project } = useProjectContext()
const kpsEnabled = useFlag('initWithKps')
useEffect(() => {
@@ -47,4 +45,4 @@ const PageLayout: NextPageWithLayout = ({}) => {
PageLayout.getLayout = (page) => <StorageLayout title="Buckets">{page}</StorageLayout>
-export default observer(PageLayout)
+export default PageLayout
diff --git a/studio/pages/project/[ref]/storage/policies.tsx b/studio/pages/project/[ref]/storage/policies.tsx
index 09d5f8d667f..f1809b04734 100644
--- a/studio/pages/project/[ref]/storage/policies.tsx
+++ b/studio/pages/project/[ref]/storage/policies.tsx
@@ -1,24 +1,23 @@
-import React, { useEffect } from 'react'
-import { useRouter } from 'next/router'
import { observer } from 'mobx-react-lite'
+import { useEffect } from 'react'
-import { API_URL } from 'lib/constants'
-import { post } from 'lib/common/fetch'
-import { PROJECT_STATUS } from 'lib/constants'
-import { useFlag, useStore } from 'hooks'
+import { useParams } from 'common'
import { StorageLayout } from 'components/layouts'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { StoragePolicies } from 'components/to-be-cleaned/Storage'
+import { useFlag, useStore } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL, PROJECT_STATUS } from 'lib/constants'
import { NextPageWithLayout } from 'types'
/**
* PageLayout is used to setup layout - as usual it will requires inject global store
*/
const PageLayout: NextPageWithLayout = () => {
- const router = useRouter()
- const { ref } = router.query
+ const { ref } = useParams()
- const { ui, meta } = useStore()
- const project = ui.selectedProject
+ const { meta } = useStore()
+ const { project } = useProjectContext()
const kpsEnabled = useFlag('initWithKps')
diff --git a/studio/pages/projects.tsx b/studio/pages/projects.tsx
index 7fb12d0342b..9d935f075f7 100644
--- a/studio/pages/projects.tsx
+++ b/studio/pages/projects.tsx
@@ -2,17 +2,22 @@ import ProjectList from 'components/interfaces/Home/ProjectList'
import { AccountLayout } from 'components/layouts'
import OrganizationDropdown from 'components/to-be-cleaned/Dropdown/OrganizationDropdown'
import Connecting from 'components/ui/Loading/Loading'
-import { useStore } from 'hooks'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useAutoProjectsPrefetch } from 'data/projects/projects-query'
import { IS_PLATFORM } from 'lib/constants'
-import { observer } from 'mobx-react-lite'
import { NextPageWithLayout } from 'types'
const ProjectsPage: NextPageWithLayout = () => {
- const { app } = useStore()
+ const { data: organizations, isLoading: _isLoading } = useOrganizationsQuery()
+ useAutoProjectsPrefetch()
+
+ // We'll continue the loading state if there's no organizations
+ // because we're waiting for the default organization to be created
+ const isLoading = _isLoading || (organizations?.length ?? 0) <= 0
return (
<>
- {!app.organizations.isInitialized ? (
+ {isLoading ? (
<div className="flex h-full items-center justify-center space-x-2">
<Connecting />
</div>
@@ -22,7 +27,7 @@ const ProjectsPage: NextPageWithLayout = () => {
<div className="my-2">
<div className="flex">
<div className="">
- <OrganizationDropdown organizations={app.organizations} />
+ <OrganizationDropdown organizations={organizations} />
</div>
</div>
</div>
@@ -50,4 +55,4 @@ ProjectsPage.getLayout = (page) => (
</AccountLayout>
)
-export default observer(ProjectsPage)
+export default ProjectsPage
diff --git a/studio/pages/vercel/integrate.tsx b/studio/pages/vercel/integrate.tsx
index 8f138bbfe8e..48885764496 100644
--- a/studio/pages/vercel/integrate.tsx
+++ b/studio/pages/vercel/integrate.tsx
@@ -1,31 +1,31 @@
+import Divider from 'components/ui/Divider'
+import { makeAutoObservable, runInAction } from 'mobx'
+import { observer, useLocalObservable } from 'mobx-react-lite'
import Link from 'next/link'
+import { useRouter } from 'next/router'
import { ChangeEvent, createContext, FC, useContext, useEffect, useState } from 'react'
import { toast } from 'react-hot-toast'
-import { useRouter } from 'next/router'
-import { observer, useLocalObservable } from 'mobx-react-lite'
-import { makeAutoObservable, runInAction } from 'mobx'
-import { Button, Select, IconPlusCircle, IconX, IconChevronRight, Listbox } from 'ui'
-import Divider from 'components/ui/Divider'
+import { Button, IconChevronRight, IconPlusCircle, IconX, Listbox, Select } from 'ui'
import { Dictionary } from 'components/grid'
-
-import { useStore, withAuth } from 'hooks'
-import { API_URL } from 'lib/constants'
-import { get } from 'lib/common/fetch'
-import {
- VERCEL_INTEGRATION_CONFIGS,
- VERCEL_DEFAULT_EXTERNAL_ID,
- INTEGRATION_ENVS_ALIAS,
-} from 'lib/vercelConfigs'
+import VercelIntegrationLayout from 'components/layouts/VercelIntegrationLayout'
import {
createVercelEnv,
fetchVercelProjectEnvs,
fetchVercelProjects,
prepareVercelEvns,
} from 'components/to-be-cleaned/Integration/Vercel.utils'
+import { databaseIcon, vercelIcon } from 'components/to-be-cleaned/ListIcons'
import Loading from 'components/ui/Loading'
-import VercelIntegrationLayout from 'components/layouts/VercelIntegrationLayout'
-import { vercelIcon, databaseIcon } from 'components/to-be-cleaned/ListIcons'
+import { useProjectsQuery } from 'data/projects/projects-query'
+import { useStore, withAuth } from 'hooks'
+import { get } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import {
+ INTEGRATION_ENVS_ALIAS,
+ VERCEL_DEFAULT_EXTERNAL_ID,
+ VERCEL_INTEGRATION_CONFIGS,
+} from 'lib/vercelConfigs'
interface IVercelIntegrationStore {
code: string
@@ -177,9 +177,8 @@ type VercelIntegrationProps = {} & any
const VercelIntegration: FC<VercelIntegrationProps> = ({}) => {
// @ts-ignore
const _store: IVercelIntegrationStore = useLocalObservable(() => new VercelIntegrationStore())
- const { app } = useStore()
- const projects = app.projects.list()
- const isSupabaseProjectListEmpty = projects.length == 0
+ const { data: projects } = useProjectsQuery()
+ const isSupabaseProjectListEmpty = !projects || projects?.length === 0
useEffect(() => {
_store.loadInitialData()
@@ -522,8 +521,7 @@ const ProjectLinkItem: FC<ProjectLinkItemProps> = observer(
const _store = useContext(PageContext)
const selectedVercelProject = _store.vercelProjects.find((x) => x.id == vercelProjectId)
- const { app } = useStore()
- const sortedProjects = app.projects.list()
+ const { data: projects } = useProjectsQuery()
function onVercelProjectChange(e: string) {
const value = e != UNDEFINED_SELECT_VALUE ? e : undefined
@@ -591,7 +589,7 @@ const ProjectLinkItem: FC<ProjectLinkItemProps> = observer(
<Listbox.Option value={UNDEFINED_SELECT_VALUE} label="Choose a project" disabled>
Choose a project
</Listbox.Option>
- {sortedProjects?.map((x: Dictionary<any>) => (
+ {projects?.map((x: Dictionary<any>) => (
<Listbox.Option
key={x.id}
value={x.ref}
diff --git a/studio/pages/vercel/setupOrg.tsx b/studio/pages/vercel/setupOrg.tsx
index 00413581948..fa47213c7ab 100644
--- a/studio/pages/vercel/setupOrg.tsx
+++ b/studio/pages/vercel/setupOrg.tsx
@@ -1,13 +1,14 @@
-import { createContext, useEffect, useContext, useState, ChangeEvent } from 'react'
-import { useRouter } from 'next/router'
-import { observer, useLocalObservable } from 'mobx-react-lite'
-import { Button, Input, Select } from 'ui'
import { runInAction } from 'mobx'
+import { observer, useLocalObservable } from 'mobx-react-lite'
+import { useRouter } from 'next/router'
+import { ChangeEvent, createContext, useContext, useEffect, useState } from 'react'
-import { API_URL } from 'lib/constants'
-import { post } from 'lib/common/fetch'
-import { useStore } from 'hooks'
import VercelIntegrationLayout from 'components/layouts/VercelIntegrationLayout'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useStore } from 'hooks'
+import { post } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { Button, Input, Select } from 'ui'
const PageContext = createContext(null)
function SetupOrg() {
@@ -53,14 +54,13 @@ function SetupOrg() {
},
}))
- const { app } = useStore()
+ const { data: organizations } = useOrganizationsQuery()
useEffect(() => {
PageState.loadInitialData()
- const sortedOrganizations = app.organizations.list()
- PageState.shouldShowOrgCreationUI = sortedOrganizations?.length == 0
- }, [])
+ PageState.shouldShowOrgCreationUI = organizations?.length == 0
+ }, [organizations])
return (
// @ts-ignore
@@ -78,7 +78,7 @@ const CreateOrganization = observer(({}) => {
const router = useRouter()
const { ui, app } = useStore()
- const sortedOrganizations = app.organizations.list()
+ const { data: organizations } = useOrganizationsQuery()
const [orgName, setOrgName] = useState('')
const [loading, setLoading] = useState(false)
@@ -109,7 +109,7 @@ const CreateOrganization = observer(({}) => {
return (
<div className="">
- {sortedOrganizations?.length > 0 ? (
+ {(organizations?.length ?? 0) > 0 ? (
<p className="mb-2">Create a new organization</p>
) : (
<>
@@ -141,14 +141,13 @@ const OrgSelection = observer(({}) => {
const router = useRouter()
const [loading, setLoading] = useState(false)
- const { app } = useStore()
- const sortedOrganizations = app.organizations.list()
+ const { data: organizations } = useOrganizationsQuery()
useEffect(() => {
if (!PageState.selectedOrg) {
- PageState.selectedOrg = sortedOrganizations?.length > 0 ? sortedOrganizations[0] : undefined
+ PageState.selectedOrg = (organizations?.length ?? 0) > 0 ? organizations?.[0] : undefined
}
- }, [sortedOrganizations])
+ }, [organizations])
function onContinue() {
setLoading(true)
@@ -164,7 +163,7 @@ const OrgSelection = observer(({}) => {
}
function onOrgSelect(e: ChangeEvent<HTMLSelectElement>) {
- const selectedOrg = sortedOrganizations.find((x: any) => x.slug === e.target.value)
+ const selectedOrg = organizations?.find((x: any) => x.slug === e.target.value)
PageState.selectedOrg = selectedOrg
}
@@ -176,7 +175,7 @@ const OrgSelection = observer(({}) => {
value={PageState.selectedOrg?.slug}
onChange={onOrgSelect}
>
- {sortedOrganizations?.map((x) => {
+ {organizations?.map((x) => {
return (
<Select.Option key={x.id} value={x.slug}>
{x.name}