Skip to content

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

Refactor to change mutateAsync to mutate

Joshen Lima07b762cabc8
diff --git a/studio/components/grid/components/header/Header.tsx b/studio/components/grid/components/header/Header.tsx
index 3c267a5d76d..a1abc2d270c 100644
--- a/studio/components/grid/components/header/Header.tsx
+++ b/studio/components/grid/components/header/Header.tsx
@@ -235,9 +235,43 @@ const RowHeader = ({ table, sorts, filters }: RowHeaderProps) => {
const { project } = useProjectContext()
// [Joshen] Passing blank error handlers here as the errors are handled via the
// error handler in tracked state within catch block
- const { mutateAsync: deleteRows } = useTableRowDeleteMutation({ onError: () => {} })
- const { mutateAsync: deleteAllRows } = useTableRowDeleteAllMutation({ onError: () => {} })
- const { mutateAsync: truncateRows } = useTableRowTruncateMutation({ onError: () => {} })
+ const { mutateAsync: deleteRows } = useTableRowDeleteMutation({
+ onSuccess: (res, variables) => {
+ const rowIdxs = variables.rows.map((x) => x.idx)
+ dispatch({ type: 'REMOVE_ROWS', payload: { rowIdxs } })
+ dispatch({
+ type: 'SELECTED_ROWS_CHANGE',
+ payload: { selectedRows: new Set() },
+ })
+ },
+ onError: (error) => {
+ if (state.onError) state.onError(error)
+ },
+ })
+ const { mutateAsync: deleteAllRows } = useTableRowDeleteAllMutation({
+ onSuccess: () => {
+ dispatch({ type: 'REMOVE_ALL_ROWS' })
+ dispatch({
+ type: 'SELECTED_ROWS_CHANGE',
+ payload: { selectedRows: new Set() },
+ })
+ },
+ onError: (error) => {
+ if (state.onError) state.onError(error)
+ },
+ })
+ const { mutateAsync: truncateRows } = useTableRowTruncateMutation({
+ onSuccess: () => {
+ dispatch({ type: 'REMOVE_ALL_ROWS' })
+ dispatch({
+ type: 'SELECTED_ROWS_CHANGE',
+ payload: { selectedRows: new Set() },
+ })
+ },
+ onError: (error) => {
+ if (state.onError) state.onError(error)
+ },
+ })
const { data } = useTableRowsQuery({
queryKey: [table.schema, table.name],
@@ -288,28 +322,20 @@ const RowHeader = ({ table, sorts, filters }: RowHeaderProps) => {
if (allRowsSelected) {
try {
if (filters.length === 0) {
- await truncateRows({
+ truncateRows({
projectRef: project.ref,
connectionString: project.connectionString,
table,
})
} else {
- await deleteAllRows({
+ deleteAllRows({
projectRef: project.ref,
connectionString: project.connectionString,
table,
filters,
})
}
-
- dispatch({ type: 'REMOVE_ALL_ROWS' })
- dispatch({
- type: 'SELECTED_ROWS_CHANGE',
- payload: { selectedRows: new Set() },
- })
- } catch (error) {
- if (state.onError) state.onError(error)
- }
+ } catch (error) {}
} else {
const rowIdxs = Array.from(selectedRows) as number[]
const rows = allRows.filter((x) => rowIdxs.includes(x.idx))
@@ -321,15 +347,7 @@ const RowHeader = ({ table, sorts, filters }: RowHeaderProps) => {
table,
rows,
})
-
- dispatch({ type: 'REMOVE_ROWS', payload: { rowIdxs } })
- dispatch({
- type: 'SELECTED_ROWS_CHANGE',
- payload: { selectedRows: new Set() },
- })
- } catch (error) {
- if (state.onError) state.onError(error)
- }
+ } catch (error) {}
}
},
})
diff --git a/studio/components/grid/components/menu/RowContextMenu.tsx b/studio/components/grid/components/menu/RowContextMenu.tsx
index 1b5e02013f3..074e1255598 100644
--- a/studio/components/grid/components/menu/RowContextMenu.tsx
+++ b/studio/components/grid/components/menu/RowContextMenu.tsx
@@ -19,9 +19,18 @@ const RowContextMenu = ({ table, rows }: RowContextMenuProps) => {
const dispatch = useDispatch()
const { project } = useProjectContext()
- // [Joshen] Passing blank error handlers here as the errors are handled via the
- // error handler in tracked state within catch block
- const { mutateAsync: deleteRows } = useTableRowDeleteMutation({ onError: () => {} })
+ const { mutate: deleteRows } = useTableRowDeleteMutation({
+ onSuccess: (res, variables) => {
+ dispatch({ type: 'REMOVE_ROWS', payload: { rowIdxs: [variables.rows[0].idx] } })
+ dispatch({
+ type: 'SELECTED_ROWS_CHANGE',
+ payload: { selectedRows: new Set() },
+ })
+ },
+ onError: (error) => {
+ if (state.onError) state.onError(error)
+ },
+ })
function onDeleteRow(p: ItemParams) {
confirmAlert({
@@ -33,22 +42,12 @@ const RowContextMenu = ({ table, rows }: RowContextMenuProps) => {
const row = rows[rowIdx]
if (!row || !project) return
- try {
- await deleteRows({
- projectRef: project.ref,
- connectionString: project.connectionString,
- table,
- rows: [row],
- })
-
- dispatch({ type: 'REMOVE_ROWS', payload: { rowIdxs: [row.idx] } })
- dispatch({
- type: 'SELECTED_ROWS_CHANGE',
- payload: { selectedRows: new Set() },
- })
- } catch (error) {
- if (state.onError) state.onError(error)
- }
+ deleteRows({
+ projectRef: project.ref,
+ connectionString: project.connectionString,
+ table,
+ rows: [row],
+ })
},
})
}
diff --git a/studio/components/interfaces/Account/AccessTokenList.tsx b/studio/components/interfaces/Account/AccessTokenList.tsx
index ee0b3d501f2..5746aab2995 100644
--- a/studio/components/interfaces/Account/AccessTokenList.tsx
+++ b/studio/components/interfaces/Account/AccessTokenList.tsx
@@ -6,18 +6,22 @@ import { Button, IconTrash, Modal } from 'ui'
import Table from 'components/to-be-cleaned/Table'
import ConfirmationModal from 'components/ui/ConfirmationModal'
+import { useStore } from 'hooks'
const AccessTokenList = observer(() => {
+ const { ui } = useStore()
const { data: tokens, isLoading } = useAccessTokensQuery()
- const { mutateAsync: deleteToken } = useAccessTokenDeleteMutation()
+ const { mutate: deleteToken } = useAccessTokenDeleteMutation({
+ onSuccess: () => {
+ ui.setNotification({ category: 'success', message: 'Successfully deleted access token' })
+ setIsOpen(false)
+ },
+ })
const [isOpen, setIsOpen] = useState(false)
const [token, setToken] = useState<AccessToken | undefined>(undefined)
- async function onDeleteToken(tokenId: number) {
- await deleteToken({ id: tokenId })
- setIsOpen(false)
- }
+ const onDeleteToken = async (tokenId: number) => deleteToken({ id: tokenId })
return (
<>
@@ -78,6 +82,7 @@ const AccessTokenList = observer(() => {
danger={true}
header="Confirm to delete"
buttonLabel="Delete"
+ buttonLoadingLabel="Deleting"
onSelectCancel={() => setIsOpen(false)}
onSelectConfirm={() => {
if (token) onDeleteToken(token.id)
diff --git a/studio/components/interfaces/Account/NewAccessTokenButton.tsx b/studio/components/interfaces/Account/NewAccessTokenButton.tsx
index 118ba182444..e3b7e9eeabd 100644
--- a/studio/components/interfaces/Account/NewAccessTokenButton.tsx
+++ b/studio/components/interfaces/Account/NewAccessTokenButton.tsx
@@ -1,8 +1,9 @@
-import { useState } from 'react'
-import { Input, Button, Modal, Form, Alert, IconChevronDown, Dropdown, IconExternalLink } from 'ui'
-import { useAccessTokenCreateMutation } from 'data/access-tokens/access-tokens-create-mutation'
import { observer } from 'mobx-react-lite'
import Link from 'next/link'
+import { useState } from 'react'
+import { Alert, Button, Dropdown, Form, IconChevronDown, IconExternalLink, Input, Modal } from 'ui'
+
+import { useAccessTokenCreateMutation } from 'data/access-tokens/access-tokens-create-mutation'
export interface NewAccessTokenButtonProps {
onCreateToken: (token: any) => void
@@ -18,12 +19,15 @@ const NewAccessTokenButton = observer(({ onCreateToken }: NewAccessTokenButtonPr
return errors
}
- const { mutateAsync: createAccessToken, isLoading } = useAccessTokenCreateMutation()
+ const { mutate: createAccessToken, isLoading } = useAccessTokenCreateMutation({
+ onSuccess: (res) => {
+ onCreateToken(res)
+ setIsOpen(false)
+ },
+ })
- async function onFormSubmit(values: any) {
- const response = await createAccessToken({ name: values.tokenName, scope: tokenScope })
- onCreateToken(response)
- setIsOpen(false)
+ const onFormSubmit = async (values: any) => {
+ createAccessToken({ name: values.tokenName, scope: tokenScope })
}
return (
diff --git a/studio/components/interfaces/Auth/Users/CreateUserModal.tsx b/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
index 018e091db00..81ad96fa4e0 100644
--- a/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
+++ b/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
@@ -41,8 +41,13 @@ const CreateUserModal = ({ visible, setVisible }: CreateUserModalProps) => {
return errors
}
- const { mutateAsync: createUser, isLoading: isCreatingUser } = useUserCreateMutation({
- async onSuccess() {
+ const { mutate: createUser, isLoading: isCreatingUser } = useUserCreateMutation({
+ async onSuccess(res) {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully created user: ${res.email}`,
+ })
+ setVisible(false)
await PageState.fetchData(1)
},
})
@@ -56,17 +61,7 @@ const CreateUserModal = ({ visible, setVisible }: CreateUserModalProps) => {
}
const { protocol, endpoint, serviceApiKey } = data.autoApiService
- await createUser({
- endpoint,
- protocol,
- serviceApiKey,
- user: values,
- })
- ui.setNotification({
- category: 'success',
- message: `Successfully created user: ${values.email}`,
- })
- setVisible(false)
+ createUser({ endpoint, protocol, serviceApiKey, user: values })
}
return (
diff --git a/studio/components/interfaces/BillingV2/Subscription/CostControl/SpendCapSidePanel.tsx b/studio/components/interfaces/BillingV2/Subscription/CostControl/SpendCapSidePanel.tsx
index f1437f84e29..10456fc3732 100644
--- a/studio/components/interfaces/BillingV2/Subscription/CostControl/SpendCapSidePanel.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/CostControl/SpendCapSidePanel.tsx
@@ -53,8 +53,20 @@ const SpendCapSidePanel = () => {
const onClose = () => snap.setPanelKey(undefined)
const { data: subscription, isLoading } = useProjectSubscriptionV2Query({ projectRef })
- const { mutateAsync: updateSubscriptionTier, isLoading: isUpdating } =
+ const isFreePlan = subscription?.plan?.id === 'free'
+ const isSpendCapOn = !subscription?.usage_billing_enabled
+ const isTurningOnCap = !isSpendCapOn && selectedOption === 'on'
+ const hasChanges = selectedOption !== (isSpendCapOn ? 'on' : 'off')
+
+ const { mutate: updateSubscriptionTier, isLoading: isUpdating } =
useProjectSubscriptionUpdateMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully ${isTurningOnCap ? 'enabled' : 'disabled'} spend cap`,
+ })
+ onClose()
+ },
onError: (error) => {
ui.setNotification({
error,
@@ -64,11 +76,6 @@ const SpendCapSidePanel = () => {
},
})
- const isFreePlan = subscription?.plan?.id === 'free'
- const isSpendCapOn = !subscription?.usage_billing_enabled
- const isTurningOnCap = !isSpendCapOn && selectedOption === 'on'
- const hasChanges = selectedOption !== (isSpendCapOn ? 'on' : 'off')
-
useEffect(() => {
if (visible && subscription !== undefined) {
setSelectedOption(isSpendCapOn ? 'on' : 'off')
@@ -93,12 +100,7 @@ const SpendCapSidePanel = () => {
const tier = (
selectedOption === 'on' ? PRICING_TIER_PRODUCT_IDS.PRO : PRICING_TIER_PRODUCT_IDS.PAYG
) as 'tier_pro' | 'tier_payg'
- await updateSubscriptionTier({ projectRef, tier })
- ui.setNotification({
- category: 'success',
- message: `Successfully ${isTurningOnCap ? 'enabled' : 'disabled'} spend cap`,
- })
- onClose()
+ updateSubscriptionTier({ projectRef, tier })
}
const billingMetricCategories: (keyof typeof pricing)[] = [
diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx
index b0445dd0c28..634bc2aaa0f 100644
--- a/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx
@@ -84,8 +84,12 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {
// If compute instance is present within the existing subscription, then a restart will be triggered
if (!projectRef) return console.error('Project ref is required')
- await updateSubscriptionTier({ projectRef, tier: 'tier_free' })
- resetCaptcha()
+ try {
+ await updateSubscriptionTier({ projectRef, tier: 'tier_free' })
+ resetCaptcha()
+ } catch (error) {
+ return
+ }
try {
const feedbackRes = await post(`${API_URL}/feedback/downgrade`, {
diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/TierUpdateSidePanel.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/TierUpdateSidePanel.tsx
index 07b826a5118..2472ed8332c 100644
--- a/studio/components/interfaces/BillingV2/Subscription/Tier/TierUpdateSidePanel.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/TierUpdateSidePanel.tsx
@@ -48,8 +48,18 @@ const TierUpdateSidePanel = () => {
const { data: subscription } = useProjectSubscriptionV2Query({ projectRef })
const { data: addons } = useProjectAddonsQuery({ projectRef })
const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery({ slug })
- const { mutateAsync: updateSubscriptionTier, isLoading: isUpdating } =
- useProjectSubscriptionUpdateMutation()
+ const { mutate: updateSubscriptionTier, isLoading: isUpdating } =
+ useProjectSubscriptionUpdateMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully updated subscription to ${selectedTierMeta?.name}!`,
+ })
+ setSelectedTier(undefined)
+ onClose()
+ window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
+ },
+ })
const availablePlans = plans ?? []
const subscriptionAddons = addons?.selected_addons ?? []
@@ -94,18 +104,11 @@ const TierUpdateSidePanel = () => {
return ui.setNotification({ category: 'error', message: 'Please select a payment method' })
}
- await updateSubscriptionTier({
+ updateSubscriptionTier({
projectRef,
tier: selectedTier,
paymentMethod: selectedPaymentMethod,
})
- ui.setNotification({
- category: 'success',
- message: `Successfully updated subscription to ${selectedTierMeta?.name}!`,
- })
- setSelectedTier(undefined)
- onClose()
- window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
}
return (
diff --git a/studio/components/interfaces/Database/Hooks/DeleteHookModal.tsx b/studio/components/interfaces/Database/Hooks/DeleteHookModal.tsx
index 8970c8d4008..83ce67e1054 100644
--- a/studio/components/interfaces/Database/Hooks/DeleteHookModal.tsx
+++ b/studio/components/interfaces/Database/Hooks/DeleteHookModal.tsx
@@ -16,8 +16,14 @@ const DeleteHookModal = ({ selectedHook, visible, onClose }: DeleteHookModalProp
const { id, name, schema } = selectedHook ?? {}
const { project } = useProjectContext()
- const { mutateAsync: deleteDatabaseTrigger, isLoading: isDeleting } =
- useDatabaseTriggerDeleteMutation()
+ const { mutate: deleteDatabaseTrigger, isLoading: isDeleting } = useDatabaseTriggerDeleteMutation(
+ {
+ onSuccess: () => {
+ ui.setNotification({ category: 'success', message: `Successfully deleted ${name}` })
+ onClose()
+ },
+ }
+ )
async function handleDelete() {
if (!project) {
@@ -27,13 +33,11 @@ const DeleteHookModal = ({ selectedHook, visible, onClose }: DeleteHookModalProp
return ui.setNotification({ category: 'error', message: 'Unable find selected hook' })
}
- await deleteDatabaseTrigger({
+ deleteDatabaseTrigger({
id,
projectRef: project.ref,
connectionString: project.connectionString,
})
- ui.setNotification({ category: 'success', message: `Successfully deleted ${name}` })
- onClose()
}
return (
diff --git a/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx b/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
index a2d811e01e9..bae48fe938a 100644
--- a/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
+++ b/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
@@ -45,9 +45,16 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =
const { project } = useProjectContext()
const { data: functions } = useEdgeFunctionsQuery({ projectRef: ref })
- const { mutateAsync: createDatabaseTrigger, isLoading: isCreatingDatabaseTrigger } =
+ const { mutate: createDatabaseTrigger, isLoading: isCreatingDatabaseTrigger } =
useDatabaseTriggerCreateMutation({
- onError(error) {
+ onSuccess: (res) => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully created new webhook "${res.name}"`,
+ })
+ onClose()
+ },
+ onError: (error) => {
ui.setNotification({
error,
category: 'error',
@@ -55,9 +62,16 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =
})
},
})
- const { mutateAsync: updateDatabaseTrigger, isLoading: isUpdatingDatabaseTrigger } =
+ const { mutate: updateDatabaseTrigger, isLoading: isUpdatingDatabaseTrigger } =
useDatabaseTriggerUpdateMutation({
- onError(error) {
+ onSuccess: (res) => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully updated webhook "${res.name}"`,
+ })
+ onClose()
+ },
+ onError: (error) => {
ui.setNotification({
error,
category: 'error',
@@ -211,23 +225,13 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =
connectionString: project?.connectionString,
payload,
})
- ui.setNotification({
- category: 'success',
- message: `Successfully created new webhook "${values.name}"`,
- })
- onClose()
} else {
- await updateDatabaseTrigger({
+ updateDatabaseTrigger({
projectRef: project?.ref,
connectionString: project?.connectionString,
originalTrigger: selectedHook,
updatedTrigger: payload,
})
- ui.setNotification({
- category: 'success',
- message: `Successfully updated webhook "${values.name}"`,
- })
- onClose()
}
}
diff --git a/studio/components/interfaces/Database/Wrappers/CreateWrapper.tsx b/studio/components/interfaces/Database/Wrappers/CreateWrapper.tsx
index 90308810c50..d8716b1b1c7 100644
--- a/studio/components/interfaces/Database/Wrappers/CreateWrapper.tsx
+++ b/studio/components/interfaces/Database/Wrappers/CreateWrapper.tsx
@@ -1,28 +1,28 @@
-import Link from 'next/link'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import { isEmpty } from 'lodash'
-import { useState } from 'react'
-import { useRouter } from 'next/router'
import { observer } from 'mobx-react-lite'
-import { Button, Form, Input, IconArrowLeft, IconExternalLink, IconEdit, IconTrash } from 'ui'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
+import Link from 'next/link'
+import { useRouter } from 'next/router'
+import { useState } from 'react'
+import { Button, Form, IconArrowLeft, IconEdit, IconExternalLink, IconTrash, Input } from 'ui'
-import { useCheckPermissions, useStore } from 'hooks'
import { useParams } from 'common/hooks'
import {
- FormPanel,
FormActions,
+ FormPanel,
FormSection,
- FormsContainer,
- FormSectionLabel,
FormSectionContent,
+ FormSectionLabel,
+ FormsContainer,
} from 'components/ui/Forms'
import { useFDWCreateMutation } from 'data/fdw/fdw-create-mutation'
+import { useCheckPermissions, useStore } from 'hooks'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import InputField from './InputField'
-import { WRAPPERS } from './Wrappers.constants'
import WrapperTableEditor from './WrapperTableEditor'
+import { WRAPPERS } from './Wrappers.constants'
import { makeValidateRequired } from './Wrappers.utils'
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
const CreateWrapper = () => {
const formId = 'create-wrapper-form'
@@ -30,14 +30,27 @@ const CreateWrapper = () => {
const { ui, meta } = useStore()
const { ref, type } = useParams()
const { project } = useProjectContext()
- const { mutateAsync: createFDW, isLoading: isCreating } = useFDWCreateMutation()
+ const canCreateWrapper = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'wrappers')
const [newTables, setNewTables] = useState<any[]>([])
const [isEditingTable, setIsEditingTable] = useState(false)
const [selectedTableToEdit, setSelectedTableToEdit] = useState()
const [formErrors, setFormErrors] = useState<{ [k: string]: string }>({})
- const canCreateWrapper = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'wrappers')
+ const { mutate: createFDW, isLoading: isCreating } = useFDWCreateMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully created ${wrapperMeta?.label} foreign data wrapper`,
+ })
+ setNewTables([])
+
+ const hasNewSchema = newTables.some((table) => table.is_new_schema)
+ if (hasNewSchema) meta.schemas.load()
+
+ router.push(`/project/${ref}/database/wrappers`)
+ },
+ })
const wrapperMeta = WRAPPERS.find((wrapper) => wrapper.name === type)
const initialValues =
@@ -95,23 +108,13 @@ const CreateWrapper = () => {
if (newTables.length === 0) errors.tables = 'Please add at least one table'
if (!isEmpty(errors)) return setFormErrors(errors)
- await createFDW({
+ createFDW({
projectRef: project?.ref,
connectionString: project?.connectionString,
wrapperMeta,
formState: { ...values, server_name: `${wrapper_name}_server` },
tables: newTables,
})
- ui.setNotification({
- category: 'success',
- message: `Successfully created ${wrapperMeta.label} foreign data wrapper`,
- })
- setNewTables([])
-
- const hasNewSchema = newTables.some((table) => table.is_new_schema)
- if (hasNewSchema) meta.schemas.load()
-
- router.push(`/project/${ref}/database/wrappers`)
}
return (
diff --git a/studio/components/interfaces/Database/Wrappers/DeleteWrapperModal.tsx b/studio/components/interfaces/Database/Wrappers/DeleteWrapperModal.tsx
index e55e0c7456b..a6ab8041e05 100644
--- a/studio/components/interfaces/Database/Wrappers/DeleteWrapperModal.tsx
+++ b/studio/components/interfaces/Database/Wrappers/DeleteWrapperModal.tsx
@@ -13,7 +13,15 @@ interface DeleteWrapperModalProps {
const DeleteWrapperModal = ({ selectedWrapper, onClose }: DeleteWrapperModalProps) => {
const { ui } = useStore()
const { project } = useProjectContext()
- const { mutateAsync: deleteFDW, isLoading: isDeleting } = useFDWDeleteMutation()
+ const { mutate: deleteFDW, isLoading: isDeleting } = useFDWDeleteMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully disabled ${selectedWrapper?.name} foreign data wrapper`,
+ })
+ onClose()
+ },
+ })
const wrapperMeta = WRAPPERS.find((meta) => meta.handlerName === selectedWrapper?.handler)
const onConfirmDelete = async () => {
@@ -21,18 +29,12 @@ const DeleteWrapperModal = ({ selectedWrapper, onClose }: DeleteWrapperModalProp
if (!selectedWrapper) return console.error('Wrapper is required')
if (!wrapperMeta) return console.error('Wrapper meta is required')
- await deleteFDW({
+ deleteFDW({
projectRef: project?.ref,
connectionString: project?.connectionString,
wrapper: selectedWrapper,
wrapperMeta: wrapperMeta,
})
-
- ui.setNotification({
- category: 'success',
- message: `Successfully disabled ${selectedWrapper.name} foreign data wrapper`,
- })
- onClose()
}
return (
diff --git a/studio/components/interfaces/Database/Wrappers/EditWrapper.tsx b/studio/components/interfaces/Database/Wrappers/EditWrapper.tsx
index 40c935da19f..a91247a6c77 100644
--- a/studio/components/interfaces/Database/Wrappers/EditWrapper.tsx
+++ b/studio/components/interfaces/Database/Wrappers/EditWrapper.tsx
@@ -58,7 +58,20 @@ const EditWrapper = () => {
const wrapper = useImmutableValue(foundWrapper)
const wrapperMeta = WRAPPERS.find((w) => w.handlerName === wrapper?.handler)
- const { mutateAsync: updateFDW, isLoading: isSaving } = useFDWUpdateMutation()
+ const { mutate: updateFDW, isLoading: isSaving } = useFDWUpdateMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully updated ${wrapperMeta?.label} foreign data wrapper`,
+ })
+ setWrapperTables([])
+
+ const hasNewSchema = wrapperTables.some((table) => table.is_new_schema)
+ if (hasNewSchema) meta.schemas.load()
+
+ router.push(`/project/${ref}/database/wrappers`)
+ },
+ })
const [wrapperTables, setWrapperTables] = useState<any[]>([])
const [isEditingTable, setIsEditingTable] = useState(false)
@@ -145,7 +158,7 @@ const EditWrapper = () => {
if (wrapperTables.length === 0) errors.tables = 'Please add at least one table'
if (!isEmpty(errors)) return setFormErrors(errors)
- await updateFDW({
+ updateFDW({
projectRef: project?.ref,
connectionString: project?.connectionString,
wrapper,
@@ -153,17 +166,6 @@ const EditWrapper = () => {
formState: { ...values, server_name: `${wrapper_name}_server` },
tables: wrapperTables,
})
-
- ui.setNotification({
- category: 'success',
- message: `Successfully updated ${wrapperMeta.label} foreign data wrapper`,
- })
- setWrapperTables([])
-
- const hasNewSchema = wrapperTables.some((table) => table.is_new_schema)
- if (hasNewSchema) meta.schemas.load()
-
- router.push(`/project/${ref}/database/wrappers`)
}
return (
diff --git a/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx b/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
index 6b7055ace13..a601e794816 100644
--- a/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
+++ b/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
@@ -46,7 +46,15 @@ const EdgeFunctionDetails = () => {
const { data: settings } = useProjectApiQuery({ projectRef })
const { data: selectedFunction } = useEdgeFunctionQuery({ projectRef, slug: functionSlug })
const { mutateAsync: updateEdgeFunction, isLoading: isUpdating } = useEdgeFunctionUpdateMutation()
- const { mutateAsync: deleteEdgeFunction, isLoading: isDeleting } = useEdgeFunctionDeleteMutation()
+ const { mutate: deleteEdgeFunction, isLoading: isDeleting } = useEdgeFunctionDeleteMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully deleted "${selectedFunction?.name}"`,
+ })
+ router.push(`/project/${projectRef}/functions`)
+ },
+ })
const formId = 'edge-function-update-form'
const canUpdateEdgeFunction = useCheckPermissions(PermissionAction.FUNCTIONS_WRITE, '*')
@@ -70,25 +78,21 @@ const EdgeFunctionDetails = () => {
if (!projectRef) return console.error('Project ref is required')
if (selectedFunction === undefined) return console.error('No edge function selected')
- await updateEdgeFunction({
- projectRef,
- slug: selectedFunction.slug,
- payload: values,
- })
- resetForm({ values, initialValues: values })
- ui.setNotification({ category: 'success', message: `Successfully updated edge function` })
+ try {
+ await updateEdgeFunction({
+ projectRef,
+ slug: selectedFunction.slug,
+ payload: values,
+ })
+ resetForm({ values, initialValues: values })
+ ui.setNotification({ category: 'success', message: `Successfully updated edge function` })
+ } catch (error) {}
}
const onConfirmDelete = async () => {
if (!projectRef) return console.error('Project ref is required')
if (selectedFunction === undefined) return console.error('No edge function selected')
-
- await deleteEdgeFunction({ projectRef, slug: selectedFunction.slug })
- ui.setNotification({
- category: 'success',
- message: `Successfully deleted "${selectedFunction.name}"`,
- })
- router.push(`/project/${projectRef}/functions`)
+ deleteEdgeFunction({ projectRef, slug: selectedFunction.slug })
}
const hasImportMap = useMemo(
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/BillingAddress/BillingAddress.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/BillingAddress/BillingAddress.tsx
index b111b287705..c35082667d2 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/BillingAddress/BillingAddress.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/BillingAddress/BillingAddress.tsx
@@ -43,12 +43,14 @@ const BillingAddress = () => {
const onSubmit = async (values: any, { resetForm }: any) => {
if (!slug) return console.error('Slug is required')
- await updateCustomerProfile({ slug, address: values })
- ui.setNotification({
- category: 'success',
- message: 'Successfully updated billing address',
- })
- resetForm({ values, initialValues: values })
+ try {
+ await updateCustomerProfile({ slug, address: values })
+ ui.setNotification({
+ category: 'success',
+ message: 'Successfully updated billing address',
+ })
+ resetForm({ values, initialValues: values })
+ } catch (error) {}
}
return (
@@ -56,7 +58,9 @@ const BillingAddress = () => {
<ScaffoldSectionDetail>
<div className="sticky top-16">
<p className="text-base">Billing Address</p>
- <p className="text-sm text-scale-1000">This will be reflected in every upcoming invoice, past invoices are not affected</p>
+ <p className="text-sm text-scale-1000">
+ This will be reflected in every upcoming invoice, past invoices are not affected
+ </p>
</div>
</ScaffoldSectionDetail>
<ScaffoldSectionContent>
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/BillingEmail.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/BillingEmail.tsx
index d6fee530281..130960f0e2f 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/BillingEmail.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/BillingEmail.tsx
@@ -38,17 +38,19 @@ const BillingEmail = () => {
if (!slug) return console.error('Slug is required')
if (!name) return console.error('Organization name is required')
- const { billing_email } = await updateOrganization({
- slug,
- billing_email: values.billing_email,
- name,
- })
- resetForm({ values: { billing_email }, initialValues: { billing_email } })
- invalidateOrganizationsQuery(queryClient)
- ui.setNotification({
- category: 'success',
- message: 'Successfully saved settings',
- })
+ try {
+ const { billing_email } = await updateOrganization({
+ slug,
+ billing_email: values.billing_email,
+ name,
+ })
+ resetForm({ values: { billing_email }, initialValues: { billing_email } })
+ invalidateOrganizationsQuery(queryClient)
+ ui.setNotification({
+ category: 'success',
+ message: 'Successfully saved settings',
+ })
+ } catch (error) {}
}
return (
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/SpendCapSidePanel.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/SpendCapSidePanel.tsx
index 32eba0c0ff2..382a0985258 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/SpendCapSidePanel.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/SpendCapSidePanel.tsx
@@ -53,8 +53,16 @@ const SpendCapSidePanel = () => {
const onClose = () => snap.setPanelKey(undefined)
const { data: subscription, isLoading } = useOrgSubscriptionQuery({ orgSlug: slug })
- const { mutateAsync: updateOrgSubscription, isLoading: isUpdating } =
- useOrgSubscriptionUpdateMutation({
+ const { mutate: updateOrgSubscription, isLoading: isUpdating } = useOrgSubscriptionUpdateMutation(
+ {
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully ${isTurningOnCap ? 'enabled' : 'disabled'} spend cap`,
+ })
+
+ onClose()
+ },
onError: (error) => {
ui.setNotification({
error,
@@ -62,7 +70,8 @@ const SpendCapSidePanel = () => {
message: `Failed to toggle spend cap: ${error.message}`,
})
},
- })
+ }
+ )
const isFreePlan = subscription?.plan?.id === 'free'
const isSpendCapOn = !subscription?.usage_billing_enabled
@@ -95,14 +104,7 @@ const SpendCapSidePanel = () => {
selectedOption === 'on' ? PRICING_TIER_PRODUCT_IDS.PRO : PRICING_TIER_PRODUCT_IDS.PAYG
) as 'tier_pro' | 'tier_payg'
- await updateOrgSubscription({ slug, tier })
-
- ui.setNotification({
- category: 'success',
- message: `Successfully ${isTurningOnCap ? 'enabled' : 'disabled'} spend cap`,
- })
-
- onClose()
+ updateOrgSubscription({ slug, tier })
}
const billingMetricCategories: (keyof typeof pricing)[] = [
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/ChangePaymentMethodModal.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/ChangePaymentMethodModal.tsx
index f4a56b273d2..a58f2f57cd1 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/ChangePaymentMethodModal.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/ChangePaymentMethodModal.tsx
@@ -20,15 +20,25 @@ const ChangePaymentMethodModal = ({
const { ui } = useStore()
const { slug } = useParams()
const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: slug })
- const { mutateAsync: updateOrgSubscription, isLoading: isUpdating } =
- useOrgSubscriptionUpdateMutation({
+ const { mutate: updateOrgSubscription, isLoading: isUpdating } = useOrgSubscriptionUpdateMutation(
+ {
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully changed payment method to the card ending with ${
+ selectedPaymentMethod!.card.last4
+ }`,
+ })
+ onClose()
+ },
onError: (error) => {
ui.setNotification({
category: 'error',
message: `Failed to change payment method: ${error.message}`,
})
},
- })
+ }
+ )
const onConfirmUpdate = async () => {
if (!slug) return console.error('Slug is required')
@@ -40,16 +50,11 @@ const ChangePaymentMethodModal = ({
? 'tier_payg'
: `tier_${subscription.plan.id}`
- await updateOrgSubscription({
+ updateOrgSubscription({
slug,
tier: selectedTier as SubscriptionTier,
paymentMethod: selectedPaymentMethod.id,
})
- ui.setNotification({
- category: 'success',
- message: `Successfully changed payment method to the card ending with ${selectedPaymentMethod.card.last4}`,
- })
- onClose()
}
return (
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/DeletePaymentMethodModal.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/DeletePaymentMethodModal.tsx
index d5fe34da0fe..cc05e5f1b6b 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/DeletePaymentMethodModal.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/DeletePaymentMethodModal.tsx
@@ -16,19 +16,23 @@ const DeletePaymentMethodModal = ({
const { ui } = useStore()
const { slug } = useParams()
- const { mutateAsync: deletePayment, isLoading: isDeleting } =
- useOrganizationPaymentMethodDeleteMutation()
+ const { mutate: deletePayment, isLoading: isDeleting } =
+ useOrganizationPaymentMethodDeleteMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully removed payment method ending with ${
+ selectedPaymentMethod!.card.last4
+ }`,
+ })
+ onClose()
+ },
+ })
const onConfirmDelete = async () => {
if (!slug) return console.error('Slug is required')
if (!selectedPaymentMethod) return console.error('Card ID is required')
-
- await deletePayment({ slug, cardId: selectedPaymentMethod.id })
- ui.setNotification({
- category: 'success',
- message: `Successfully removed payment method ending with ${selectedPaymentMethod.card.last4}`,
- })
- onClose()
+ deletePayment({ slug, cardId: selectedPaymentMethod.id })
}
return (
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
index eccadbc1c83..5b197f7bd9b 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
@@ -47,8 +47,17 @@ const PlanUpdateSidePanel = () => {
const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: slug })
const { data: plans, isLoading: isLoadingPlans } = useOrgPlansQuery({ orgSlug: slug })
const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery({ slug })
- const { mutateAsync: updateOrgSubscription, isLoading: isUpdating } =
- useOrgSubscriptionUpdateMutation({
+ const { mutate: updateOrgSubscription, isLoading: isUpdating } = useOrgSubscriptionUpdateMutation(
+ {
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully updated subscription to ${subscriptionPlanMeta?.name}!`,
+ })
+ setSelectedTier(undefined)
+ onClose()
+ window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
+ },
onError: (error) => {
ui.setNotification({
error,
@@ -56,7 +65,8 @@ const PlanUpdateSidePanel = () => {
message: `Unable to update subscription: ${error.message}`,
})
},
- })
+ }
+ )
const availablePlans = plans ?? []
const hasMembersExceedingFreeTierLimit = (membersExceededLimit || []).length > 0
@@ -100,18 +110,7 @@ const PlanUpdateSidePanel = () => {
return ui.setNotification({ category: 'error', message: 'Please select a payment method' })
}
- await updateOrgSubscription({
- slug,
- tier: selectedTier,
- paymentMethod: selectedPaymentMethod,
- })
- ui.setNotification({
- category: 'success',
- message: `Successfully updated subscription to ${subscriptionPlanMeta?.name}!`,
- })
- setSelectedTier(undefined)
- onClose()
- window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
+ updateOrgSubscription({ slug, tier: selectedTier, paymentMethod: selectedPaymentMethod })
}
return (
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/TaxID/TaxID.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/TaxID/TaxID.tsx
index ae9d62b0e39..6e5f4c6d1c2 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/TaxID/TaxID.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/TaxID/TaxID.tsx
@@ -32,7 +32,33 @@ const TaxID = () => {
isSuccess,
isError,
} = useOrganizationTaxIDsQuery({ slug })
- const { mutateAsync: updateTaxIDs, isLoading: isUpdating } = useOrganizationTaxIDsUpdateMutation()
+ const { mutate: updateTaxIDs, isLoading: isUpdating } = useOrganizationTaxIDsUpdateMutation({
+ onSuccess: (res) => {
+ const { created, errors } = res
+ setErrors(errors?.map((taxId) => taxId.id) ?? [])
+ const updatedTaxIds =
+ created?.map((x) => {
+ return {
+ id: x.id,
+ type: x.type,
+ value: x.value,
+ name:
+ x.type === 'eu_vat'
+ ? `${x.country} VAT`
+ : TAX_IDS.find((option) => option.code === x.type)?.name ?? '',
+ }
+ }) ?? []
+ setTaxIdValues(updatedTaxIds)
+
+ if (errors !== undefined && errors.length > 0) {
+ errors.forEach((taxId: any) => {
+ ui.setNotification({ category: 'error', message: taxId.result.error.message })
+ })
+ } else {
+ ui.setNotification({ category: 'success', message: 'Successfully updated tax IDs' })
+ }
+ },
+ })
const [errors, setErrors] = useState<string[]>([])
const [taxIdValues, setTaxIdValues] = useState<TaxIdValue[]>([])
@@ -102,30 +128,7 @@ const TaxID = () => {
if (taxIds === undefined) return console.error('Tax IDs are required')
const newIds = taxIdValues.map((x) => sanitizeTaxID(x))
- const { created, errors } = await updateTaxIDs({ slug, existingIds: taxIds, newIds })
- setErrors(errors?.map((taxId) => taxId.id) ?? [])
-
- const updatedTaxIds =
- created?.map((x) => {
- return {
- id: x.id,
- type: x.type,
- value: x.value,
- name:
- x.type === 'eu_vat'
- ? `${x.country} VAT`
- : TAX_IDS.find((option) => option.code === x.type)?.name ?? '',
- }
- }) ?? []
- setTaxIdValues(updatedTaxIds)
-
- if (errors !== undefined && errors.length > 0) {
- errors.forEach((taxId: any) => {
- ui.setNotification({ category: 'error', message: taxId.result.error.message })
- })
- } else {
- ui.setNotification({ category: 'success', message: 'Successfully updated tax IDs' })
- }
+ updateTaxIDs({ slug, existingIds: taxIds, newIds })
}
return (
diff --git a/studio/components/interfaces/Organization/GeneralSettings/MigrateOrganizationBillingButton.tsx b/studio/components/interfaces/Organization/GeneralSettings/MigrateOrganizationBillingButton.tsx
index 266d4182f72..fb36c0f1c4b 100644
--- a/studio/components/interfaces/Organization/GeneralSettings/MigrateOrganizationBillingButton.tsx
+++ b/studio/components/interfaces/Organization/GeneralSettings/MigrateOrganizationBillingButton.tsx
@@ -1,5 +1,7 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { observer } from 'mobx-react-lite'
+import Link from 'next/link'
+import { useRouter } from 'next/router'
import { useEffect, useMemo, useState } from 'react'
import { Alert, Button, Form, IconHelpCircle, Listbox, Loading, Modal, Toggle } from 'ui'
@@ -8,8 +10,6 @@ import { useOrganizationBillingMigrationMutation } from 'data/organizations/orga
import { useOrganizationBillingMigrationPreview } from 'data/organizations/organization-migrate-billing-preview-query'
import { useCheckPermissions, useSelectedOrganization, useStore } from 'hooks'
import { PRICING_TIER_LABELS_ORG } from 'lib/constants'
-import Link from 'next/link'
-import { useRouter } from 'next/router'
const MigrateOrganizationBillingButton = observer(() => {
const { ui } = useStore()
@@ -33,9 +33,19 @@ const MigrateOrganizationBillingButton = observer(() => {
const {
error: migrationError,
- mutateAsync: migrateBilling,
+ mutate: migrateBilling,
isLoading: isMigrating,
- } = useOrganizationBillingMigrationMutation()
+ } = useOrganizationBillingMigrationMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ message: 'Successfully migrated to organization-level billing',
+ category: 'success',
+ duration: 5000,
+ })
+ router.push('/projects')
+ setIsOpen(false)
+ },
+ })
const {
data: migrationPreviewData,
@@ -86,14 +96,7 @@ const MigrateOrganizationBillingButton = observer(() => {
})
}
- await migrateBilling({ organizationSlug: organization?.slug, tier: dbTier })
- ui.setNotification({
- message: 'Successfully migrated to organization-level billing',
- category: 'success',
- duration: 5000,
- })
- router.push('/projects')
- setIsOpen(false)
+ migrateBilling({ organizationSlug: organization?.slug, tier: dbTier })
}
return (
diff --git a/studio/components/interfaces/Organization/OAuthApps/DeleteAppModal.tsx b/studio/components/interfaces/Organization/OAuthApps/DeleteAppModal.tsx
index 7e72ca16a5e..aa9a5a6ed49 100644
--- a/studio/components/interfaces/Organization/OAuthApps/DeleteAppModal.tsx
+++ b/studio/components/interfaces/Organization/OAuthApps/DeleteAppModal.tsx
@@ -12,18 +12,20 @@ export interface DeleteAppModalProps {
const DeleteAppModal = ({ selectedApp, onClose }: DeleteAppModalProps) => {
const { ui } = useStore()
const { slug } = useParams()
- const { mutateAsync: deleteOAuthApp, isLoading: isDeleting } = useOAuthAppDeleteMutation()
+ const { mutate: deleteOAuthApp, isLoading: isDeleting } = useOAuthAppDeleteMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully deleted the app "${selectedApp?.name}"`,
+ })
+ onClose()
+ },
+ })
const onConfirmDelete = async () => {
if (!slug) return console.error('Slug is required')
if (!selectedApp?.id) return console.error('App ID is required')
-
- await deleteOAuthApp({ slug, id: selectedApp?.id })
- ui.setNotification({
- category: 'success',
- message: `Successfully deleted the app "${selectedApp?.name}"`,
- })
- onClose()
+ deleteOAuthApp({ slug, id: selectedApp?.id })
}
return (
diff --git a/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel.tsx b/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel.tsx
index 6ed4b3a5cb6..2ee0a6fe602 100644
--- a/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel.tsx
+++ b/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel.tsx
@@ -30,8 +30,43 @@ const PublishAppSidePanel = ({
const { ui } = useStore()
const { slug } = useParams()
const uploadButtonRef = useRef<any>()
- const { mutateAsync: createOAuthApp } = useOAuthAppCreateMutation()
- const { mutateAsync: updateOAuthApp } = useOAuthAppUpdateMutation()
+ const { mutate: createOAuthApp } = useOAuthAppCreateMutation({
+ onSuccess: (res, variables) => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully created OAuth app "${variables.name}"!`,
+ })
+ onClose()
+ onCreateSuccess(res)
+ setIsSubmitting(false)
+ },
+ onError: (error) => {
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to create OAuth application: ${error.message}`,
+ })
+ setIsSubmitting(false)
+ },
+ })
+ const { mutate: updateOAuthApp } = useOAuthAppUpdateMutation({
+ onSuccess: (res, variables) => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully updated OAuth app "${variables.name}"!`,
+ })
+ onClose()
+ setIsSubmitting(false)
+ },
+ onError: (error) => {
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to update OAuth application: ${error.message}`,
+ })
+ setIsSubmitting(false)
+ },
+ })
// [Joshen] Separate submitting state as there are additional async logic involved in the creation
const [isSubmitting, setIsSubmitting] = useState(false)
@@ -109,42 +144,25 @@ const PublishAppSidePanel = ({
? await uploadAttachment('oauth-app-icons', `${slug}/${uuidv4()}.png`, iconFile)
: iconUrl
- try {
- if (selectedApp === undefined) {
- // Create application
- const res = await createOAuthApp({
- slug,
- name,
- website,
- redirect_uris,
- icon: uploadedIconUrl,
- })
- ui.setNotification({
- category: 'success',
- message: `Successfully created OAuth app "${name}"!`,
- })
- onClose()
- onCreateSuccess(res)
- } else {
- // Update application
- await updateOAuthApp({
- id: selectedApp.id,
- slug,
- name,
- website,
- redirect_uris,
- icon: uploadedIconUrl === undefined ? null : uploadedIconUrl,
- })
- ui.setNotification({
- category: 'success',
- message: `Successfully updated OAuth app "${name}"!`,
- })
- onClose()
- setIsSubmitting(false)
- }
- } catch (error) {
- } finally {
- setIsSubmitting(false)
+ if (selectedApp === undefined) {
+ // Create application
+ createOAuthApp({
+ slug,
+ name,
+ website,
+ redirect_uris,
+ icon: uploadedIconUrl,
+ })
+ } else {
+ // Update application
+ updateOAuthApp({
+ id: selectedApp.id,
+ slug,
+ name,
+ website,
+ redirect_uris,
+ icon: uploadedIconUrl === undefined ? null : uploadedIconUrl,
+ })
}
}
diff --git a/studio/components/interfaces/Organization/OAuthApps/RevokeAppModal.tsx b/studio/components/interfaces/Organization/OAuthApps/RevokeAppModal.tsx
index 6d38c843a15..aa500cfbb92 100644
--- a/studio/components/interfaces/Organization/OAuthApps/RevokeAppModal.tsx
+++ b/studio/components/interfaces/Organization/OAuthApps/RevokeAppModal.tsx
@@ -12,19 +12,20 @@ export interface RevokeAppModalProps {
const RevokeAppModal = ({ selectedApp, onClose }: RevokeAppModalProps) => {
const { ui } = useStore()
const { slug } = useParams()
- const { mutateAsync: revokeAuthorizedApp, isLoading: isDeleting } =
- useAuthorizedAppRevokeMutation()
+ const { mutate: revokeAuthorizedApp, isLoading: isDeleting } = useAuthorizedAppRevokeMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully revoked the app "${selectedApp?.name}"`,
+ })
+ onClose()
+ },
+ })
const onConfirmDelete = async () => {
if (!slug) return console.error('Slug is required')
if (!selectedApp?.id) return console.error('App ID is required')
-
- await revokeAuthorizedApp({ slug, id: selectedApp?.id })
- ui.setNotification({
- category: 'success',
- message: `Successfully revoked the app "${selectedApp?.name}"`,
- })
- onClose()
+ revokeAuthorizedApp({ slug, id: selectedApp?.id })
}
return (
diff --git a/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx b/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx
index 23df6df5c15..9d01e5e1dcb 100644
--- a/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx
+++ b/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx
@@ -72,21 +72,22 @@ const InviteMemberButton = ({
}
const roleId = Number(values.role)
- const response = await inviteMember({
- slug,
- invitedEmail: values.email.toLowerCase(),
- ownerId: userId,
- roleId,
- })
- if (isNil(response)) {
- ui.setNotification({ category: 'error', message: 'Failed to add member' })
- } else {
- ui.setNotification({ category: 'success', message: 'Successfully added new member.' })
-
- setIsOpen(!isOpen)
- resetForm({ initialValues: { ...initialValues, role: roleId } })
- }
+ try {
+ const response = await inviteMember({
+ slug,
+ invitedEmail: values.email.toLowerCase(),
+ ownerId: userId,
+ roleId,
+ })
+ if (isNil(response)) {
+ ui.setNotification({ category: 'error', message: 'Failed to add member' })
+ } else {
+ ui.setNotification({ category: 'success', message: 'Successfully added new member.' })
+ setIsOpen(!isOpen)
+ resetForm({ initialValues: { ...initialValues, role: roleId } })
+ }
+ } catch (error) {}
}
return (
diff --git a/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx b/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx
index 0d1a49f531d..180f16f771a 100644
--- a/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx
+++ b/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx
@@ -42,16 +42,24 @@ const MemberActions = ({ member, roles }: MemberActionsProps) => {
resource: { role_id: roleId },
})
- const {
- mutateAsync: deleteOrganizationMemberAsync,
- isLoading: isOrganizationMemberDeleteLoading,
- } = useOrganizationMemberDeleteMutation()
+ const { mutate: deleteOrganizationMember, isLoading: isOrganizationMemberDeleteLoading } =
+ useOrganizationMemberDeleteMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully removed ${member.primary_email}`,
+ })
+ },
+ })
const {
- mutateAsync: createOrganizationMemberInvite,
+ mutate: createOrganizationMemberInvite,
isLoading: isOrganizationMemberInviteCreateLoading,
} = useOrganizationMemberInviteCreateMutation({
- onError(error) {
+ onSuccess: () => {
+ ui.setNotification({ category: 'success', message: 'Resent the invitation.' })
+ },
+ onError: (error) => {
ui.setNotification({
category: 'error',
message: `Failed to resend invitation: ${error.message}`,
@@ -60,9 +68,13 @@ const MemberActions = ({ member, roles }: MemberActionsProps) => {
})
const {
- mutateAsync: deleteOrganizationMemberInvite,
+ mutate: deleteOrganizationMemberInvite,
isLoading: isOrganizationMemberInviteDeleteLoading,
- } = useOrganizationMemberInviteDeleteMutation()
+ } = useOrganizationMemberInviteDeleteMutation({
+ onSuccess: () => {
+ ui.setNotification({ category: 'success', message: 'Successfully revoked the invitation.' })
+ },
+ })
const handleMemberDelete = async () => {
confirmAlert({
@@ -71,11 +83,7 @@ const MemberActions = ({ member, roles }: MemberActionsProps) => {
onAsyncConfirm: async () => {
if (!slug) return console.error('slug is required')
if (!member.gotrue_id) return console.error('gotrue_id is required')
- await deleteOrganizationMemberAsync({ slug, gotrueId: member.gotrue_id })
- ui.setNotification({
- category: 'success',
- message: `Successfully removed ${member.primary_email}`,
- })
+ deleteOrganizationMember({ slug, gotrueId: member.gotrue_id })
},
})
}
@@ -83,24 +91,20 @@ const MemberActions = ({ member, roles }: MemberActionsProps) => {
const handleResendInvite = async (member: Member) => {
if (!slug) return console.error('Slug is required')
if (!member.invited_id) return console.error('Member invited ID is required')
-
const roleId = (member?.role_ids ?? [])[0]
- await createOrganizationMemberInvite({
+ createOrganizationMemberInvite({
slug,
invitedEmail: member.primary_email,
ownerId: member.invited_id,
roleId: roleId,
})
- ui.setNotification({ category: 'success', message: 'Resent the invitation.' })
}
const handleRevokeInvitation = async (member: Member) => {
const invitedId = member.invited_id
if (!slug) return console.error('Slug is required')
if (!invitedId) return console.error('Member invited ID is required')
-
- await deleteOrganizationMemberInvite({ slug, invitedId })
- ui.setNotification({ category: 'success', message: 'Successfully revoked the invitation.' })
+ deleteOrganizationMemberInvite({ slug, invitedId })
}
if (!canRemoveMember || (isPendingInviteAcceptance && !canResendInvite && !canRevokeInvite)) {
diff --git a/studio/components/interfaces/Organization/TeamSettings/MembersView.tsx b/studio/components/interfaces/Organization/TeamSettings/MembersView.tsx
index f4333c9e7fd..8d30a6d915b 100644
--- a/studio/components/interfaces/Organization/TeamSettings/MembersView.tsx
+++ b/studio/components/interfaces/Organization/TeamSettings/MembersView.tsx
@@ -49,8 +49,9 @@ const MembersView = ({ searchString }: MembersViewProps) => {
isLoading: isLoadingRoles,
isError: isErrorRoles,
} = useOrganizationRolesQuery({ slug })
- const { mutateAsync: updateOrganizationMember, isLoading } = useOrganizationMemberUpdateMutation({
+ const { mutate: updateOrganizationMember, isLoading } = useOrganizationMemberUpdateMutation({
onSuccess() {
+ setUserRoleChangeModalVisible(false)
ui.setNotification({
category: 'success',
message: `Successfully updated role for ${getUserDisplayName(selectedMember)}`,
@@ -103,9 +104,7 @@ const MembersView = ({ searchString }: MembersViewProps) => {
const { gotrue_id, newRoleId } = selectedMember
if (!slug) return console.error('slug is required')
if (!gotrue_id) return console.error('gotrue_id is required')
-
- await updateOrganizationMember({ slug, gotrueId: gotrue_id, roleId: newRoleId })
- setUserRoleChangeModalVisible(false)
+ updateOrganizationMember({ slug, gotrueId: gotrue_id, roleId: newRoleId })
}
return (
diff --git a/studio/components/interfaces/Settings/API/JWTSettings.tsx b/studio/components/interfaces/Settings/API/JWTSettings.tsx
index 2a88c19c004..d0f8b0fb44f 100644
--- a/studio/components/interfaces/Settings/API/JWTSettings.tsx
+++ b/studio/components/interfaces/Settings/API/JWTSettings.tsx
@@ -71,16 +71,16 @@ const JWTSettings = () => {
setModalVisibility: Dispatch<SetStateAction<boolean>>
) {
if (!projectRef) return console.error('Project ref is required')
-
const trackingId = uuidv4()
- await updateJwt({ projectRef, jwtSecret: jwt_secret, changeTrackingId: trackingId })
-
- setModalVisibility(false)
- ui.setNotification({
- category: 'info',
- message:
- 'Successfully submitted JWT secret update request. Please wait while your project is updated.',
- })
+ try {
+ await updateJwt({ projectRef, jwtSecret: jwt_secret, changeTrackingId: trackingId })
+ setModalVisibility(false)
+ ui.setNotification({
+ category: 'info',
+ message:
+ 'Successfully submitted JWT secret update request. Please wait while your project is updated.',
+ })
+ } catch (error) {}
}
return (
diff --git a/studio/components/interfaces/Settings/API/PostgrestConfig.tsx b/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
index 0139feea6c3..57a184065df 100644
--- a/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
+++ b/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
@@ -26,7 +26,12 @@ const PostgrestConfig = () => {
const { meta } = PageState
const { data: config, isError } = useProjectPostgrestConfigQuery({ projectRef })
- const { mutateAsync: updatePostgrestConfig } = useProjectPostgrestConfigUpdateMutation()
+ const { mutate: updatePostgrestConfig, isLoading: isUpdating } =
+ useProjectPostgrestConfigUpdateMutation({
+ onSuccess: () => {
+ ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
+ },
+ })
const canUpdatePostgrestConfig = useCheckPermissions(
PermissionAction.UPDATE,
'custom_config_postgrest'
@@ -37,14 +42,12 @@ const PostgrestConfig = () => {
const updateConfig = async (updatedConfig: typeof initialValues) => {
if (!projectRef) return console.error('Project ref is required')
-
- await updatePostgrestConfig({
+ updatePostgrestConfig({
projectRef,
dbSchema: updatedConfig.db_schema,
maxRows: updatedConfig.max_rows,
dbExtraSearchPath: updatedConfig.db_extra_search_path,
})
- ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
}
const permanentSchema = ['public', 'storage']
@@ -69,7 +72,7 @@ const PostgrestConfig = () => {
return (
<Form id={formId} initialValues={initialValues} validate={() => {}} onSubmit={updateConfig}>
- {({ isSubmitting, handleReset, resetForm, values, initialValues }: any) => {
+ {({ handleReset, resetForm, values, initialValues }: any) => {
const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
// [Alaister] although this "technically" is breaking the rules of React hooks
@@ -95,7 +98,7 @@ const PostgrestConfig = () => {
<div className="flex px-8 py-4">
<FormActions
form={formId}
- isSubmitting={isSubmitting}
+ isSubmitting={isUpdating}
hasChanges={hasChanges}
handleReset={handleReset}
disabled={!canUpdatePostgrestConfig}
diff --git a/studio/components/interfaces/Settings/Addons/ComputeInstanceSidePanel.tsx b/studio/components/interfaces/Settings/Addons/ComputeInstanceSidePanel.tsx
index c88f3abbaf9..f8850e94a82 100644
--- a/studio/components/interfaces/Settings/Addons/ComputeInstanceSidePanel.tsx
+++ b/studio/components/interfaces/Settings/Addons/ComputeInstanceSidePanel.tsx
@@ -65,7 +65,17 @@ const ComputeInstanceSidePanel = () => {
const { data: addons, isLoading } = useProjectAddonsQuery({ projectRef })
const { data: subscription } = useProjectSubscriptionV2Query({ projectRef })
- const { mutateAsync: updateAddon, isLoading: isUpdating } = useProjectAddonUpdateMutation({
+ const { mutate: updateAddon, isLoading: isUpdating } = useProjectAddonUpdateMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ duration: 8000,
+ category: 'success',
+ message: `Successfully updated compute instance to ${selectedCompute?.name}. Your project is currently being restarted to update its instance`,
+ })
+ setProjectStatus(queryClient, projectRef!, PROJECT_STATUS.RESTORING)
+ onClose()
+ router.push(`/project/${projectRef}`)
+ },
onError: (error) => {
ui.setNotification({
error,
@@ -74,7 +84,17 @@ const ComputeInstanceSidePanel = () => {
})
},
})
- const { mutateAsync: removeAddon, isLoading: isRemoving } = useProjectAddonRemoveMutation({
+ const { mutate: removeAddon, isLoading: isRemoving } = useProjectAddonRemoveMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ duration: 8000,
+ category: 'success',
+ message: `Successfully updated compute instance to Micro. Your project is currently being restarted to update its instance`,
+ })
+ setProjectStatus(queryClient, projectRef!, PROJECT_STATUS.RESTORING)
+ onClose()
+ router.push(`/project/${projectRef}`)
+ },
onError: (error) => {
ui.setNotification({
error,
@@ -129,21 +149,10 @@ const ComputeInstanceSidePanel = () => {
if (!projectId) return console.error('Project ID is required')
if (selectedOption === 'ci_micro' && subscriptionCompute !== undefined) {
- await removeAddon({ projectRef, variant: subscriptionCompute.variant.identifier })
+ removeAddon({ projectRef, variant: subscriptionCompute.variant.identifier })
} else {
- await updateAddon({ projectRef, type: 'compute_instance', variant: selectedOption })
+ updateAddon({ projectRef, type: 'compute_instance', variant: selectedOption })
}
-
- ui.setNotification({
- duration: 8000,
- category: 'success',
- message: `Successfully updated compute instance to ${
- selectedCompute?.name || 'Micro'
- }. Your project is currently being restarted to update its instance`,
- })
- setProjectStatus(queryClient, projectRef, PROJECT_STATUS.RESTORING)
- onClose()
- router.push(`/project/${projectRef}`)
}
return (
diff --git a/studio/components/interfaces/Settings/Addons/CustomDomainSidePanel.tsx b/studio/components/interfaces/Settings/Addons/CustomDomainSidePanel.tsx
index a24830dffcf..ed3a3240a09 100644
--- a/studio/components/interfaces/Settings/Addons/CustomDomainSidePanel.tsx
+++ b/studio/components/interfaces/Settings/Addons/CustomDomainSidePanel.tsx
@@ -34,21 +34,35 @@ const CustomDomainSidePanel = () => {
const { data: addons, isLoading } = useProjectAddonsQuery({ projectRef })
const { data: subscription } = useProjectSubscriptionV2Query({ projectRef })
- const { mutateAsync: updateAddon, isLoading: isUpdating } = useProjectAddonUpdateMutation({
+ const { mutate: updateAddon, isLoading: isUpdating } = useProjectAddonUpdateMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully enabled custom domain`,
+ })
+ onClose()
+ },
onError: (error) => {
ui.setNotification({
error,
category: 'error',
- message: `Unable to update custom domain: ${error.message}`,
+ message: `Unable to enable custom domain: ${error.message}`,
})
},
})
- const { mutateAsync: removeAddon, isLoading: isRemoving } = useProjectAddonRemoveMutation({
+ const { mutate: removeAddon, isLoading: isRemoving } = useProjectAddonRemoveMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully disabled custom domain`,
+ })
+ onClose()
+ },
onError: (error) => {
ui.setNotification({
error,
category: 'error',
- message: `Unable to update custom domain: ${error.message}`,
+ message: `Unable to disable custom domain: ${error.message}`,
})
},
})
@@ -90,20 +104,11 @@ const CustomDomainSidePanel = () => {
const onConfirm = async () => {
if (!projectRef) return console.error('Project ref is required')
-
if (selectedOption === 'cd_none' && subscriptionCDOption !== undefined) {
- await removeAddon({ projectRef, variant: subscriptionCDOption.variant.identifier })
+ removeAddon({ projectRef, variant: subscriptionCDOption.variant.identifier })
} else {
- await updateAddon({ projectRef, type: 'custom_domain', variant: selectedOption })
+ updateAddon({ projectRef, type: 'custom_domain', variant: selectedOption })
}
-
- ui.setNotification({
- category: 'success',
- message: `Successfully ${
- selectedOption === 'cd_none' ? 'disabled' : 'enabled'
- } custom domain`,
- })
- onClose()
}
return (
diff --git a/studio/components/interfaces/Settings/Addons/PITRSidePanel.tsx b/studio/components/interfaces/Settings/Addons/PITRSidePanel.tsx
index 55948e4d23e..7249d8297e1 100644
--- a/studio/components/interfaces/Settings/Addons/PITRSidePanel.tsx
+++ b/studio/components/interfaces/Settings/Addons/PITRSidePanel.tsx
@@ -55,7 +55,14 @@ const PITRSidePanel = () => {
const { data: addons, isLoading } = useProjectAddonsQuery({ projectRef })
const { data: subscription } = useProjectSubscriptionV2Query({ projectRef })
- const { mutateAsync: updateAddon, isLoading: isUpdating } = useProjectAddonUpdateMutation({
+ const { mutate: updateAddon, isLoading: isUpdating } = useProjectAddonUpdateMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully updated point in time recovery duration`,
+ })
+ onClose()
+ },
onError: (error) => {
ui.setNotification({
error,
@@ -64,12 +71,19 @@ const PITRSidePanel = () => {
})
},
})
- const { mutateAsync: removeAddon, isLoading: isRemoving } = useProjectAddonRemoveMutation({
+ const { mutate: removeAddon, isLoading: isRemoving } = useProjectAddonRemoveMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully disabled point in time recovery`,
+ })
+ onClose()
+ },
onError: (error) => {
ui.setNotification({
error,
category: 'error',
- message: `Unable to update PITR: ${error.message}`,
+ message: `Unable to disable PITR: ${error.message}`,
})
},
})
@@ -114,18 +128,10 @@ const PITRSidePanel = () => {
if (!projectRef) return console.error('Project ref is required')
if (selectedOption === 'pitr_0' && subscriptionPitr !== undefined) {
- await removeAddon({ projectRef, variant: subscriptionPitr.variant.identifier })
+ removeAddon({ projectRef, variant: subscriptionPitr.variant.identifier })
} else {
- await updateAddon({ projectRef, type: 'pitr', variant: selectedOption })
+ updateAddon({ projectRef, type: 'pitr', variant: selectedOption })
}
-
- ui.setNotification({
- category: 'success',
- message: `Successfully ${
- selectedOption === 'pitr_0' ? 'disabled' : 'updated'
- } point in time recovery duration`,
- })
- onClose()
}
return (
diff --git a/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx b/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx
index 4be77ab8168..41a9d2c8d0a 100644
--- a/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx
+++ b/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx
@@ -26,19 +26,21 @@ const DiskSizeConfiguration = ({ disabled = false }: DiskSizeConfigurationProps)
const { data: projectUsage } = useProjectUsageQuery({ projectRef })
const { data: projectSubscriptionData } = useProjectSubscriptionV2Query({ projectRef })
- const { mutateAsync: updateProjectUsage, isLoading: isUpdatingDiskSize } =
- useProjectDiskResizeMutation()
+ const { mutate: updateProjectUsage, isLoading: isUpdatingDiskSize } =
+ useProjectDiskResizeMutation({
+ onSuccess: (res, variables) => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully updated disk size to ${variables.volumeSize} GB`,
+ })
+ setShowResetDbPass(false)
+ },
+ })
const confirmResetDbPass = async (values: { [prop: string]: any }) => {
- const volumeSize = values['new-disk-size']
if (!projectRef) return console.error('Project ref is required')
-
- await updateProjectUsage({ projectRef, volumeSize })
- ui.setNotification({
- category: 'success',
- message: `Successfully updated disk size to ${values['new-disk-size']} GB`,
- })
- setShowResetDbPass(false)
+ const volumeSize = values['new-disk-size']
+ updateProjectUsage({ projectRef, volumeSize })
}
const currentDiskSize = projectUsage?.disk_volume_size_gb ?? 0
diff --git a/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx b/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx
index 0b6ec624e33..383ddf4bf1a 100644
--- a/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx
+++ b/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx
@@ -25,8 +25,8 @@ const AddRestrictionModal = ({
const formId = 'add-restriction-form'
const { ui } = useStore()
const { ref } = useParams()
- const { mutateAsync: applyNetworkRestrictions, isLoading: isApplying } =
- useNetworkRestrictionsApplyMutation()
+ const { mutate: applyNetworkRestrictions, isLoading: isApplying } =
+ useNetworkRestrictionsApplyMutation({ onSuccess: () => onClose() })
const validate = (values: any) => {
const errors: any = {}
@@ -62,9 +62,7 @@ const AddRestrictionModal = ({
}
const dbAllowedCidrs = hasOverachingRestriction ? [cidr] : [...restrictedIps, cidr]
-
- await applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs })
- onClose()
+ applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs })
}
return (
diff --git a/studio/components/interfaces/Settings/Database/NetworkRestrictions/AllowAllModal.tsx b/studio/components/interfaces/Settings/Database/NetworkRestrictions/AllowAllModal.tsx
index 714d31c1e51..edb8e167824 100644
--- a/studio/components/interfaces/Settings/Database/NetworkRestrictions/AllowAllModal.tsx
+++ b/studio/components/interfaces/Settings/Database/NetworkRestrictions/AllowAllModal.tsx
@@ -11,14 +11,14 @@ interface AllowAllModalProps {
const AllowAllModal = ({ visible, onClose }: AllowAllModalProps) => {
const { ref } = useParams()
- const { mutateAsync: applyNetworkRestrictions, isLoading: isApplying } =
- useNetworkRestrictionsApplyMutation()
+ const { mutate: applyNetworkRestrictions, isLoading: isApplying } =
+ useNetworkRestrictionsApplyMutation({
+ onSuccess: () => onClose(),
+ })
const onSubmit = async () => {
if (!ref) return console.error('Project ref is required')
-
- await applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs: ['0.0.0.0/0'] })
- onClose()
+ applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs: ['0.0.0.0/0'] })
}
return (
diff --git a/studio/components/interfaces/Settings/Database/NetworkRestrictions/DisallowAllModal.tsx b/studio/components/interfaces/Settings/Database/NetworkRestrictions/DisallowAllModal.tsx
index 0fc66a6cb90..6a7d3b86aa9 100644
--- a/studio/components/interfaces/Settings/Database/NetworkRestrictions/DisallowAllModal.tsx
+++ b/studio/components/interfaces/Settings/Database/NetworkRestrictions/DisallowAllModal.tsx
@@ -11,14 +11,12 @@ interface DisallowAllModalProps {
const DisallowAllModal = ({ visible, onClose }: DisallowAllModalProps) => {
const { ref } = useParams()
- const { mutateAsync: applyNetworkRestrictions, isLoading: isApplying } =
- useNetworkRestrictionsApplyMutation()
+ const { mutate: applyNetworkRestrictions, isLoading: isApplying } =
+ useNetworkRestrictionsApplyMutation({ onSuccess: () => onClose() })
const onSubmit = async () => {
if (!ref) return console.error('Project ref is required')
-
await applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs: ['127.0.0.1/32'] })
- onClose()
}
return (
diff --git a/studio/components/interfaces/Settings/Database/NetworkRestrictions/RemoveRestrictionModal.tsx b/studio/components/interfaces/Settings/Database/NetworkRestrictions/RemoveRestrictionModal.tsx
index c995a312d5c..bcc89cb21ba 100644
--- a/studio/components/interfaces/Settings/Database/NetworkRestrictions/RemoveRestrictionModal.tsx
+++ b/studio/components/interfaces/Settings/Database/NetworkRestrictions/RemoveRestrictionModal.tsx
@@ -20,8 +20,9 @@ const RemoveRestrictionModal: FC<Props> = ({
}) => {
const { ui } = useStore()
const { ref } = useParams()
- const { mutateAsync: applyNetworkRestrictions, isLoading: isApplying } =
+ const { mutate: applyNetworkRestrictions, isLoading: isApplying } =
useNetworkRestrictionsApplyMutation({
+ onSuccess: () => onClose(),
onError: (error) => {
ui.setNotification({
category: 'error',
@@ -39,11 +40,10 @@ const RemoveRestrictionModal: FC<Props> = ({
const dbAllowedCidrs = restrictedIps.filter((ip) => ip !== selectedRestriction)
if (dbAllowedCidrs.length === 0) {
- await applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs: ['0.0.0.0/0'] })
+ applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs: ['0.0.0.0/0'] })
} else {
- await applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs })
+ applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs })
}
- onClose()
}
return (
diff --git a/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx b/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx
index 0fad2f56fd1..73d030cff5f 100644
--- a/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx
+++ b/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx
@@ -15,9 +15,10 @@ import {
import { useProjectSettingsQuery } from 'data/config/project-settings-query'
import { useSSLEnforcementQuery } from 'data/ssl-enforcement/ssl-enforcement-query'
import { useSSLEnforcementUpdateMutation } from 'data/ssl-enforcement/ssl-enforcement-update-mutation'
-import { useCheckPermissions, useFlag } from 'hooks'
+import { useCheckPermissions, useFlag, useStore } from 'hooks'
const SSLConfiguration = () => {
+ const { ui } = useStore()
const { ref } = useParams()
const [isEnforced, setIsEnforced] = useState(false)
const sslEnforcement = useFlag('sslEnforcement')
@@ -30,8 +31,18 @@ const SSLConfiguration = () => {
} = useSSLEnforcementQuery({
projectRef: ref,
})
- const { mutateAsync: updateSSLEnforcement, isLoading: isSubmitting } =
- useSSLEnforcementUpdateMutation()
+ const { mutate: updateSSLEnforcement, isLoading: isSubmitting } = useSSLEnforcementUpdateMutation(
+ {
+ onError: (error) => {
+ setIsEnforced(isEnforced)
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to update SSL enforcement: ${error.message}`,
+ })
+ },
+ }
+ )
const canUpdateSSLEnforcement = useCheckPermissions(PermissionAction.UPDATE, 'projects')
@@ -52,16 +63,8 @@ const SSLConfiguration = () => {
const toggleSSLEnforcement = async () => {
if (!ref) return console.error('Project ref is required')
-
setIsEnforced(!isEnforced)
- try {
- await updateSSLEnforcement({
- projectRef: ref,
- requestedConfig: { database: !isEnforced },
- })
- } catch (error: any) {
- setIsEnforced(isEnforced)
- }
+ updateSSLEnforcement({ projectRef: ref, requestedConfig: { database: !isEnforced } })
}
return (
diff --git a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainActivate.tsx b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainActivate.tsx
index 4167fd9562c..5eea2a0bb4d 100644
--- a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainActivate.tsx
+++ b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainActivate.tsx
@@ -19,21 +19,22 @@ const CustomDomainActivate = ({ projectRef, customDomain }: CustomDomainActivate
const { ui } = useStore()
const [isActivateConfirmModalVisible, setIsActivateConfirmModalVisible] = useState(false)
- const { mutateAsync: activateCustomDomain } = useCustomDomainActivateMutation()
- const { mutateAsync: deleteCustomDomain, isLoading: isDeleting } = useCustomDomainDeleteMutation()
+ const { mutate: activateCustomDomain } = useCustomDomainActivateMutation({
+ onSuccess: () => {
+ ui.setNotification({ category: 'success', message: `Successfully activated custom domain` })
+ setIsActivateConfirmModalVisible(false)
+ },
+ })
+ const { mutate: deleteCustomDomain, isLoading: isDeleting } = useCustomDomainDeleteMutation()
const onActivateCustomDomain = async () => {
if (!projectRef) return console.error('Project ref is required')
-
- await activateCustomDomain({ projectRef })
- ui.setNotification({ category: 'success', message: `Successfully activated custom domain` })
- setIsActivateConfirmModalVisible(false)
+ activateCustomDomain({ projectRef })
}
const onCancelCustomDomain = async () => {
if (!projectRef) return console.error('Project ref is required')
-
- await deleteCustomDomain({ projectRef })
+ deleteCustomDomain({ projectRef })
}
return (
diff --git a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainDelete.tsx b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainDelete.tsx
index 6c5adeafdd6..f1512f48028 100644
--- a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainDelete.tsx
+++ b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainDelete.tsx
@@ -17,14 +17,16 @@ export type CustomDomainDeleteProps = {
const CustomDomainDelete = ({ projectRef, customDomain }: CustomDomainDeleteProps) => {
const { ui } = useStore()
const [isDeleteConfirmModalVisible, setIsDeleteConfirmModalVisible] = useState(false)
- const { mutateAsync: deleteCustomDomain } = useCustomDomainDeleteMutation()
+ const { mutate: deleteCustomDomain } = useCustomDomainDeleteMutation({
+ onSuccess: () => {
+ ui.setNotification({ category: 'success', message: `Successfully deleted custom domain` })
+ setIsDeleteConfirmModalVisible(false)
+ },
+ })
const onDeleteCustomDomain = async () => {
if (!projectRef) return console.error('Project ref is required')
-
- await deleteCustomDomain({ projectRef })
- ui.setNotification({ category: 'success', message: `Successfully deleted custom domain` })
- setIsDeleteConfirmModalVisible(false)
+ deleteCustomDomain({ projectRef })
}
return (
diff --git a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainVerify.tsx b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainVerify.tsx
index 46c021e0a1c..ebf5ff5e3ec 100644
--- a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainVerify.tsx
+++ b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainVerify.tsx
@@ -26,7 +26,7 @@ const CustomDomainVerify = ({ projectRef, customDomain, settings }: CustomDomain
if (res.status === '2_initiated') setIsNotVerifiedYet(true)
},
})
- const { mutateAsync: deleteCustomDomain, isLoading: isDeleting } = useCustomDomainDeleteMutation()
+ const { mutate: deleteCustomDomain, isLoading: isDeleting } = useCustomDomainDeleteMutation()
const hasCAAErrors = customDomain.ssl.validation_errors?.reduce(
(acc, error) => acc || error.message.includes('caa_error'),
@@ -40,7 +40,7 @@ const CustomDomainVerify = ({ projectRef, customDomain, settings }: CustomDomain
const onCancelCustomDomain = async () => {
if (!projectRef) return console.error('Project ref is required')
- await deleteCustomDomain({ projectRef })
+ deleteCustomDomain({ projectRef })
}
return (
diff --git a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainsConfigureHostname.tsx b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainsConfigureHostname.tsx
index 5a70f7baafd..434877e5b48 100644
--- a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainsConfigureHostname.tsx
+++ b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainsConfigureHostname.tsx
@@ -23,7 +23,7 @@ const schema = yup.object({
const CustomDomainsConfigureHostname = () => {
const { ui } = useStore()
const { ref } = useParams()
- const { mutateAsync: createCustomDomain } = useCustomDomainCreateMutation()
+ const { mutate: createCustomDomain, isLoading: isCreating } = useCustomDomainCreateMutation()
const { data: settings } = useProjectApiQuery({ projectRef: ref })
const FORM_ID = 'custom-domains-form'
@@ -50,7 +50,7 @@ const CustomDomainsConfigureHostname = () => {
})
}
- await createCustomDomain({ projectRef: ref, customDomain: values.domain })
+ createCustomDomain({ projectRef: ref, customDomain: values.domain })
}
return (
@@ -60,7 +60,7 @@ const CustomDomainsConfigureHostname = () => {
validationSchema={schema}
onSubmit={onCreateCustomDomain}
>
- {({ isSubmitting, handleReset, values, initialValues }: any) => {
+ {({ handleReset, values, initialValues }: any) => {
const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
return (
@@ -71,7 +71,7 @@ const CustomDomainsConfigureHostname = () => {
<div className="flex py-4 px-8">
<FormActions
form={FORM_ID}
- isSubmitting={isSubmitting}
+ isSubmitting={isCreating}
submitText="Add"
hasChanges={hasChanges}
handleReset={handleReset}
diff --git a/studio/components/interfaces/Settings/General/General.tsx b/studio/components/interfaces/Settings/General/General.tsx
index 2dfc7b1c922..a4f2ac6b4dd 100644
--- a/studio/components/interfaces/Settings/General/General.tsx
+++ b/studio/components/interfaces/Settings/General/General.tsx
@@ -31,13 +31,11 @@ const General = () => {
const onSubmit = async (values: any, { resetForm }: any) => {
if (!project?.ref) return console.error('Ref is required')
-
- const { name } = await updateProject({ ref: project.ref, name: values.name.trim() })
- resetForm({ values: { name }, initialValues: { name } })
- ui.setNotification({
- category: 'success',
- message: 'Successfully saved settings',
- })
+ try {
+ const { name } = await updateProject({ ref: project.ref, name: values.name.trim() })
+ resetForm({ values: { name }, initialValues: { name } })
+ ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
+ } catch (error) {}
}
return (
diff --git a/studio/components/interfaces/Settings/General/TransferProjectPanel/TransferProjectButton.tsx b/studio/components/interfaces/Settings/General/TransferProjectPanel/TransferProjectButton.tsx
index 6e4e8d04d45..e6ea37f8b9a 100644
--- a/studio/components/interfaces/Settings/General/TransferProjectPanel/TransferProjectButton.tsx
+++ b/studio/components/interfaces/Settings/General/TransferProjectPanel/TransferProjectButton.tsx
@@ -1,4 +1,7 @@
-import { FC, useEffect, useMemo, useState } from 'react'
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import Link from 'next/link'
+import { useEffect, useState } from 'react'
import {
Alert,
Button,
@@ -11,16 +14,13 @@ import {
Loading,
Modal,
} from 'ui'
-import * as Tooltip from '@radix-ui/react-tooltip'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useStore, useSelectedProject, useCheckPermissions } from 'hooks'
-import { useProjectTransferPreviewQuery } from 'data/projects/project-transfer-preview-query'
-import { useProjectTransferMutation } from 'data/projects/project-transfer-mutation'
import { useOrganizationsQuery } from 'data/organizations/organizations-query'
-import Link from 'next/link'
+import { useProjectTransferMutation } from 'data/projects/project-transfer-mutation'
+import { useProjectTransferPreviewQuery } from 'data/projects/project-transfer-preview-query'
+import { useCheckPermissions, useSelectedProject, useStore } from 'hooks'
-const TransferProjectButton: FC<{}> = () => {
+const TransferProjectButton = () => {
const { ui } = useStore()
const project = useSelectedProject()
@@ -34,11 +34,22 @@ const TransferProjectButton: FC<{}> = () => {
.filter((it) => it.subscription_id)
const [isOpen, setIsOpen] = useState(false)
- const [isLoading, setIsLoading] = useState(false)
-
const [selectedOrg, setSelectedOrg] = useState()
- const { error: transferError, mutateAsync: transferProject } = useProjectTransferMutation()
+ const {
+ mutate: transferProject,
+ error: transferError,
+ isLoading: isTransferring,
+ } = useProjectTransferMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ duration: 5000,
+ message: `Successfully transferred project ${project?.name}.`,
+ })
+ setIsOpen(false)
+ },
+ })
const {
data: transferPreviewData,
@@ -47,14 +58,13 @@ const TransferProjectButton: FC<{}> = () => {
remove,
} = useProjectTransferPreviewQuery(
{ projectRef, targetOrganizationSlug: selectedOrg },
- { enabled: !isLoading && isOpen }
+ { enabled: !isTransferring && isOpen }
)
useEffect(() => {
if (isOpen) {
// reset state
setSelectedOrg(undefined)
- setIsLoading(false)
} else {
// Invalidate cache
remove()
@@ -70,21 +80,7 @@ const TransferProjectButton: FC<{}> = () => {
async function handleTransferProject() {
if (project === undefined) return
if (selectedOrg === undefined) return
-
- setIsLoading(true)
-
- try {
- await transferProject({ projectRef, targetOrganizationSlug: selectedOrg })
- ui.setNotification({
- category: 'success',
- duration: 5000,
- message: `Successfully transferred project ${project?.name}.`,
- })
- setIsOpen(false)
- } catch {
- } finally {
- setIsLoading(false)
- }
+ transferProject({ projectRef, targetOrganizationSlug: selectedOrg })
}
return (
@@ -118,7 +114,7 @@ const TransferProjectButton: FC<{}> = () => {
closable
onCancel={() => toggle()}
visible={isOpen}
- loading={isLoading}
+ loading={isTransferring}
size={'xlarge'}
header={`Transfer project ${project?.name}`}
customFooter={
@@ -129,7 +125,7 @@ const TransferProjectButton: FC<{}> = () => {
<Button
onClick={() => handleTransferProject()}
disabled={
- !transferPreviewData || !transferPreviewData.valid || isLoading || !selectedOrg
+ !transferPreviewData || !transferPreviewData.valid || isTransferring || !selectedOrg
}
>
Transfer Project
diff --git a/studio/components/interfaces/Storage/CreateBucketModal.tsx b/studio/components/interfaces/Storage/CreateBucketModal.tsx
index faea71d204b..3d098675683 100644
--- a/studio/components/interfaces/Storage/CreateBucketModal.tsx
+++ b/studio/components/interfaces/Storage/CreateBucketModal.tsx
@@ -35,7 +35,17 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {
const { ref } = useParams()
const router = useRouter()
- const { mutateAsync: createBucket, isLoading: isCreating } = useBucketCreateMutation()
+ const { mutate: createBucket, isLoading: isCreating } = useBucketCreateMutation({
+ onSuccess: (res) => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully created bucket ${res.name}`,
+ })
+ router.push(`/project/${ref}/storage/buckets/${res.name}`)
+ onClose()
+ },
+ })
+
const { data } = useProjectStorageConfigQuery({ projectRef: ref }, { enabled: IS_PLATFORM })
const { value, unit } = convertFromBytes(data?.fileSizeLimit ?? 0)
const formattedGlobalUploadLimit = `${value} ${unit}`
@@ -66,7 +76,7 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {
const onSubmit = async (values: any) => {
if (!ref) return console.error('Project ref is required')
- const res = await createBucket({
+ createBucket({
projectRef: ref,
id: values.name,
isPublic: values.public,
@@ -78,14 +88,6 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {
? values.allowed_mime_types.split(',').map((x: string) => x.trim())
: null,
})
-
- ui.setNotification({
- category: 'success',
- message: `Successfully created bucket ${res.name}`,
- })
- router.push(`/project/${ref}/storage/buckets/${res.name}`)
-
- onClose()
}
useEffect(() => {
diff --git a/studio/components/interfaces/Storage/EditBucketModal.tsx b/studio/components/interfaces/Storage/EditBucketModal.tsx
index 272f30ac079..650c68f2828 100644
--- a/studio/components/interfaces/Storage/EditBucketModal.tsx
+++ b/studio/components/interfaces/Storage/EditBucketModal.tsx
@@ -34,7 +34,15 @@ const EditBucketModal = ({ visible, bucket, onClose }: EditBucketModalProps) =>
const { ui } = useStore()
const { ref } = useParams()
- const { mutateAsync: updateBucket, isLoading: isUpdating } = useBucketUpdateMutation()
+ const { mutate: updateBucket, isLoading: isUpdating } = useBucketUpdateMutation({
+ onSuccess: () => {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully updated bucket "${bucket?.name}"`,
+ })
+ onClose()
+ },
+ })
const { data } = useProjectStorageConfigQuery({ projectRef: ref }, { enabled: IS_PLATFORM })
const { value, unit } = convertFromBytes(data?.fileSizeLimit ?? 0)
const formattedGlobalUploadLimit = `${value} ${unit}`
@@ -54,7 +62,7 @@ const EditBucketModal = ({ visible, bucket, onClose }: EditBucketModalProps) =>
if (bucket === undefined) return console.error('Bucket is required')
if (ref === undefined) return console.error('Project ref is required')
- await updateBucket({
+ updateBucket({
projectRef: ref,
id: bucket.id,
isPublic: values.public,
@@ -66,11 +74,6 @@ const EditBucketModal = ({ visible, bucket, onClose }: EditBucketModalProps) =>
? values.allowed_mime_types.split(',').map((x: string) => x.trim())
: null,
})
- ui.setNotification({
- category: 'success',
- message: `Successfully updated bucket "${bucket.name}"`,
- })
- onClose()
}
useEffect(() => {
diff --git a/studio/components/layouts/SQLEditorLayout/QueryItem.tsx b/studio/components/layouts/SQLEditorLayout/QueryItem.tsx
index 2548f273590..8deac4330f8 100644
--- a/studio/components/layouts/SQLEditorLayout/QueryItem.tsx
+++ b/studio/components/layouts/SQLEditorLayout/QueryItem.tsx
@@ -69,10 +69,15 @@ const QueryItemActions = observer(({ tabInfo, activeId }: QueryItemActionsProps)
const { ref } = useParams()
const router = useRouter()
const snap = useSqlEditorStateSnapshot()
- const { mutateAsync: deleteContent } = useContentDeleteMutation({
+ const { mutate: deleteContent } = useContentDeleteMutation({
onSuccess(data) {
- if (data.id) {
- snap.removeSnippet(data.id)
+ if (data.id) snap.removeSnippet(data.id)
+
+ const existingSnippetIds = (snap.orders[ref!] ?? []).filter((x) => x !== id)
+ if (existingSnippetIds.length === 0) {
+ router.push(`/project/${ref}/sql`)
+ } else {
+ router.push(`/project/${ref}/sql/${existingSnippetIds[0]}`)
}
},
onError(error) {
@@ -102,15 +107,7 @@ const QueryItemActions = observer(({ tabInfo, activeId }: QueryItemActionsProps)
const onConfirmDelete = async () => {
if (!ref) return console.error('Project ref is required')
if (!id) return console.error('Snippet ID is required')
-
- await deleteContent({ projectRef: ref, id })
-
- const existingSnippetIds = (snap.orders[ref] ?? []).filter((x) => x !== id)
- if (existingSnippetIds.length === 0) {
- router.push(`/project/${ref}/sql`)
- } else {
- router.push(`/project/${ref}/sql/${existingSnippetIds[0]}`)
- }
+ deleteContent({ projectRef: ref, id })
}
return (
diff --git a/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsx b/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsx
index 5d6848070a7..2371f6d6430 100644
--- a/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsx
+++ b/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsx
@@ -20,38 +20,37 @@ const DeleteBucketModal = ({ visible = false, bucket, onClose }: DeleteBucketMod
const { ref: projectRef } = useParams()
const { data } = useBucketsQuery({ projectRef })
- const { mutateAsync: deleteBucket, isLoading: isDeleting } = useBucketDeleteMutation()
+ const { mutate: deleteBucket, isLoading: isDeleting } = useBucketDeleteMutation({
+ onSuccess: async () => {
+ // Clean up policies from the corresponding bucket that was deleted
+ await meta.policies.loadBySchema('storage')
+ const policies = meta.policies.list()
+ const storageObjectsPolicies = policies.filter((policy) => policy.table === 'objects')
+ const formattedStorageObjectPolicies = formatPoliciesForStorage(
+ buckets,
+ storageObjectsPolicies
+ )
+ const bucketPolicies = _get(
+ find(formattedStorageObjectPolicies, { name: bucket!.name }),
+ ['policies'],
+ []
+ )
+ await Promise.all(bucketPolicies.map((policy: any) => meta.policies.del(policy.id)))
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully deleted bucket ${bucket!.name}`,
+ })
+ router.push(`/project/${projectRef}/storage/buckets`)
+ onClose()
+ },
+ })
const buckets = data ?? []
const onDeleteBucket = async () => {
if (!projectRef) return console.error('Project ref is required')
if (!bucket) return console.error('No bucket is selected')
-
- await deleteBucket({ projectRef, id: bucket.id })
-
- // Clean up policies from the corresponding bucket that was deleted
- await meta.policies.loadBySchema('storage')
- const policies = meta.policies.list()
- const storageObjectsPolicies = policies.filter((policy) => policy.table === 'objects')
- const formattedStorageObjectPolicies = formatPoliciesForStorage(buckets, storageObjectsPolicies)
- const bucketPolicies = _get(
- find(formattedStorageObjectPolicies, { name: bucket.name }),
- ['policies'],
- []
- )
- await Promise.all(
- bucketPolicies.map((policy: any) => {
- meta.policies.del(policy.id)
- })
- )
-
- ui.setNotification({
- category: 'success',
- message: `Successfully deleted bucket ${bucket.name}`,
- })
- router.push(`/project/${projectRef}/storage/buckets`)
- onClose()
+ deleteBucket({ projectRef, id: bucket.id })
}
return (
diff --git a/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx b/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx
index d4f3c99dd98..d79d2746bfa 100644
--- a/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx
+++ b/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx
@@ -45,7 +45,20 @@ const StorageConfig = ({ config, projectRef }: any) => {
let initialValues = { fileSizeLimit: value, unformattedFileSizeLimit: fileSizeLimit }
const canUpdateStorageSettings = useCheckPermissions(PermissionAction.STORAGE_ADMIN_WRITE, '*')
- const { mutateAsync: updateStorageConfig } = useProjectStorageConfigUpdateUpdateMutation()
+ const { mutate: updateStorageConfig, isLoading: isUpdating } =
+ useProjectStorageConfigUpdateUpdateMutation({
+ onSuccess: (res) => {
+ const updatedValue = convertFromBytes(res.fileSizeLimit)
+ initialValues = {
+ fileSizeLimit: updatedValue.value,
+ unformattedFileSizeLimit: res.fileSizeLimit,
+ }
+ ui.setNotification({
+ category: 'success',
+ message: 'Successfully updated storage settings',
+ })
+ },
+ })
const formattedMaxSizeBytes = `${new Intl.NumberFormat('en-US').format(
STORAGE_FILE_SIZE_LIMIT_MAX_BYTES
@@ -76,16 +89,10 @@ const StorageConfig = ({ config, projectRef }: any) => {
})
}
- const res = await updateStorageConfig({
+ updateStorageConfig({
projectRef,
fileSizeLimit: convertToBytes(values.fileSizeLimit, selectedUnit),
})
- const updatedValue = convertFromBytes(res.fileSizeLimit)
- initialValues = {
- fileSizeLimit: updatedValue.value,
- unformattedFileSizeLimit: res.fileSizeLimit,
- }
- ui.setNotification({ category: 'success', message: 'Successfully updated storage settings' })
}
// [Joshen] To be refactored using FormContainer, FormPanel, FormContent etc once
@@ -93,15 +100,7 @@ const StorageConfig = ({ config, projectRef }: any) => {
return (
<div className="mx-auto w-[56rem] max-w-4xl px-5 pt-12 pb-20">
<Form validateOnBlur initialValues={initialValues} validate={onValidate} onSubmit={onSubmit}>
- {({
- values,
- isSubmitting,
- handleReset,
- }: {
- values: any
- isSubmitting: boolean
- handleReset: () => void
- }) => {
+ {({ values, handleReset }: { values: any; handleReset: () => void }) => {
const hasChanges =
initialValues.unformattedFileSizeLimit !==
convertToBytes(values.fileSizeLimit, selectedUnit)
@@ -198,16 +197,18 @@ const StorageConfig = ({ config, projectRef }: any) => {
type="default"
htmlType="reset"
onClick={() => handleReset()}
- disabled={!hasChanges && hasChanges !== undefined}
+ disabled={isUpdating || (!hasChanges && hasChanges !== undefined)}
>
Cancel
</Button>
<Button
type="primary"
htmlType="submit"
- loading={isSubmitting}
+ loading={isUpdating}
disabled={
- !canUpdateStorageSettings || (!hasChanges && hasChanges !== undefined)
+ !canUpdateStorageSettings ||
+ isUpdating ||
+ (!hasChanges && hasChanges !== undefined)
}
>
Save
diff --git a/studio/components/to-be-cleaned/forms/SchemaFormPanel.js b/studio/components/to-be-cleaned/forms/SchemaFormPanel.js
index 62f37c2f18e..71d6138e2f2 100644
--- a/studio/components/to-be-cleaned/forms/SchemaFormPanel.js
+++ b/studio/components/to-be-cleaned/forms/SchemaFormPanel.js
@@ -11,6 +11,7 @@ export default function SchemaFormPanel({
onChangeModel = (model) => {},
onReset = () => {},
onSubmit,
+ loading,
submitLabel = 'Save',
cancelLabel = 'Cancel',
message = '',
@@ -64,7 +65,7 @@ export default function SchemaFormPanel({
</Button>
<Button
onClick={onClickSubmit}
- loading={submitButtonLoading}
+ loading={loading !== undefined ? loading : submitButtonLoading}
disabled={disabled || !hasChanged}
type="primary"
className="ml-2 hover:border-green-500"
diff --git a/studio/data/__templates/README.md b/studio/data/__templates/README.md
index aa6bcccf92c..d3be296edcd 100644
--- a/studio/data/__templates/README.md
+++ b/studio/data/__templates/README.md
@@ -74,8 +74,13 @@ return (
The parameter `onError` can be passed when intializing the mutation, where an appropriate UI behavior should be triggered (usually a toast will be fine). If `onError` is not provided, we will then default to a toast message that will be called from within the mutation itself which should handle most cases. However, if there is a specific way that the error should be handled, then this should be passed via the `onError` parameter. (There's no need to repeat the error handling if the default behavior is sufficient)
+We should also aim to convert most of the `mutateAsync` to `mutate`, otherwise we'd need to wrap all the `mutateAsync` calls in try catches just to ensure that the client doesn't crash when the request throws an error in the mutation. There's currently a mix due to the Form component that we're using, in particular when a method from the Form component such as `resetForm` needs to be called after the request is completed successfully.
+
```jsx
-const { mutateAsync: someAction } = useMutation({
+const { mutate: someAction } = useMutation({
+ onSuccess: (res) => {
+ ui.setNotification({ category: 'success', message: 'Success' })
+ },
onError: (error) => {
ui.setNotification({ category: 'error', message: `Failed: ${error.message}` })
},
@@ -88,7 +93,6 @@ const onConfirm = async () => {
if (!projectRef) return console.error('Project ref is required')
// Any logic before calling the mutation
- await someAction({ projectRef, otherParameters })
- // Any logic after calling the mutation
+ someAction({ projectRef, otherParameters })
}
```
diff --git a/studio/data/auth/user-create-mutation.ts b/studio/data/auth/user-create-mutation.ts
index ec362a4ac8a..c053ede01f2 100644
--- a/studio/data/auth/user-create-mutation.ts
+++ b/studio/data/auth/user-create-mutation.ts
@@ -15,6 +15,23 @@ export type UserCreateVariables = {
}
}
+export type UserCreateResponse = {
+ id: string
+ phone: string
+ role: string
+ updated_at: string
+ app_metadata: {
+ provider: string
+ providers: string[]
+ }
+ aud: string
+ created_at: string
+ email: string
+ email_confirmed_at: string
+ identities: any[]
+ user_metadata: any
+}
+
export async function createUser({ protocol, endpoint, serviceApiKey, user }: UserCreateVariables) {
const response = await post(
`${protocol}://${endpoint}/auth/v1/admin/users`,
diff --git a/studio/pages/account/me.tsx b/studio/pages/account/me.tsx
index e6f0bc5d9cd..552600090b7 100644
--- a/studio/pages/account/me.tsx
+++ b/studio/pages/account/me.tsx
@@ -42,7 +42,10 @@ export default User
const ProfileCard = observer(() => {
const { ui } = useStore()
const { profile, error, isLoading, isError, isSuccess } = useProfile()
- const { mutateAsync: updateProfile } = useProfileUpdateMutation({
+ const { mutate: updateProfile, isLoading: isUpdating } = useProfileUpdateMutation({
+ onSuccess: () => {
+ ui.setNotification({ category: 'success', message: 'Successfully saved profile' })
+ },
onError: (error) => {
ui.setNotification({
error,
@@ -53,11 +56,10 @@ const ProfileCard = observer(() => {
})
const updateUser = async (model: any) => {
- await updateProfile({
+ updateProfile({
firstName: model.first_name,
lastName: model.last_name,
})
- ui.setNotification({ category: 'success', message: 'Successfully saved profile' })
}
return (
@@ -98,6 +100,7 @@ const ProfileCard = observer(() => {
last_name: profile?.last_name ?? '',
}}
onSubmit={updateUser}
+ loading={isUpdating}
/>
</section>
</>
diff --git a/studio/pages/authorize.tsx b/studio/pages/authorize.tsx
index 41faa94974e..042083b849d 100644
--- a/studio/pages/authorize.tsx
+++ b/studio/pages/authorize.tsx
@@ -29,10 +29,17 @@ const APIAuthorizationPage: NextPageWithLayout = () => {
const isApproved = requester?.approved_at !== null
const isExpired = dayjs().isAfter(dayjs(requester?.expires_at))
- const { mutateAsync: approveRequest, isLoading: isApproving } =
- useApiAuthorizationApproveMutation()
- const { mutateAsync: declineRequest, isLoading: isDeclining } =
- useApiAuthorizationDeclineMutation()
+ const { mutate: approveRequest, isLoading: isApproving } = useApiAuthorizationApproveMutation({
+ onSuccess: (res) => {
+ router.push(res.url)
+ },
+ })
+ const { mutate: declineRequest, isLoading: isDeclining } = useApiAuthorizationDeclineMutation({
+ onSuccess: () => {
+ ui.setNotification({ category: 'success', message: 'Declined API authorization request' })
+ router.push('/projects')
+ },
+ })
const isSubmitting = isApproving || isDeclining
useEffect(() => {
@@ -55,8 +62,7 @@ const APIAuthorizationPage: NextPageWithLayout = () => {
})
}
- const res = await approveRequest({ id: auth_id, organization_id: selectedOrg })
- router.push(res.url)
+ approveRequest({ id: auth_id, organization_id: selectedOrg })
}
const onDeclineRequest = async () => {
@@ -66,9 +72,7 @@ const APIAuthorizationPage: NextPageWithLayout = () => {
message: 'Unable to decline request: auth_id is missing ',
})
- await declineRequest({ id: auth_id })
- ui.setNotification({ category: 'success', message: 'Declined API authorization request' })
- router.push('/projects')
+ declineRequest({ id: auth_id })
}
if (isLoading) {
diff --git a/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx b/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
index aa7ee41ea64..3d9872ae146 100644
--- a/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
+++ b/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
@@ -92,8 +92,13 @@ const CreateProject = ({
externalId,
} = useParams()
- const { mutateAsync: createConnections, isLoading: isLoadingCreateConnections } =
- useIntegrationConnectionsCreateMutation({})
+ const { mutate: createConnections, isLoading: isLoadingCreateConnections } =
+ useIntegrationConnectionsCreateMutation({
+ onSuccess: () => {
+ setLoading(false)
+ if (next) window.location.href = next
+ },
+ })
const { data: organizationData, isLoading: isLoadingOrganizationsQuery } = useOrganizationsQuery()
const organization = organizationData?.find((x) => x.slug === slug)
@@ -156,63 +161,50 @@ const CreateProject = ({
delayedCheckPasswordStrength(password)
}
- const { mutateAsync: createProject } = useProjectCreateMutation()
+ const { mutate: createProject } = useProjectCreateMutation({
+ onSuccess: (res) => {
+ setNewProjectRef(res.ref)
+ },
+ onError: (error) => {
+ ui.setNotification({ error, category: 'error', message: error.message })
+ setLoading(false)
+ },
+ })
const [newProjectRef, setNewProjectRef] = useState<string | undefined>(undefined)
async function onCreateProject() {
- if (!organizationIntegration) {
- console.error('No organization installation details found')
- }
-
- if (!organizationIntegration?.id) {
- console.error('No organization installation ID found')
- return
- }
-
- if (!foreignProjectId) {
- console.error('No foreignProjectId ID set')
- return
- }
-
- if (!configurationId) {
- console.error('No configurationId ID set')
- return
- }
+ if (!organizationIntegration) return console.error('No organization installation details found')
+ if (!organizationIntegration?.id) return console.error('No organization installation ID found')
+ if (!foreignProjectId) return console.error('No foreignProjectId ID set')
+ if (!configurationId) return console.error('No configurationId ID set')
+ if (!organization) return console.error('No organization ID set')
setLoading(true)
- try {
- if (!organization) throw new Error('No organization set')
-
- let dbSql: string | undefined
- if (shouldRunMigrations) {
- const id = ui.setNotification({
- category: 'info',
- message: `Fetching initial migrations from GitHub repo`,
- })
+ let dbSql: string | undefined
+ if (shouldRunMigrations) {
+ const id = ui.setNotification({
+ category: 'info',
+ message: `Fetching initial migrations from GitHub repo`,
+ })
- dbSql = (await getInitialMigrationSQLFromGitHubRepo(externalId)) ?? undefined
+ dbSql = (await getInitialMigrationSQLFromGitHubRepo(externalId)) ?? undefined
- ui.setNotification({
- id,
- category: 'success',
- message: `Done fetching initial migrations`,
- })
- }
-
- const project = await createProject({
- organizationId: organization.id,
- name: projectName,
- dbPass,
- dbRegion,
- dbSql,
- configurationId,
+ ui.setNotification({
+ id,
+ category: 'success',
+ message: `Done fetching initial migrations`,
})
- setNewProjectRef(project.ref)
- } catch (error: any) {
- ui.setNotification({ error, category: 'error', message: error.message })
- setLoading(false)
}
+
+ createProject({
+ organizationId: organization.id,
+ name: projectName,
+ dbPass,
+ dbRegion,
+ dbSql,
+ configurationId,
+ })
}
const isInstallingRef = useRef(false)
@@ -241,7 +233,7 @@ const CreateProject = ({
const projectDetails = vercelProjects?.find((x) => x.id === foreignProjectId)
- await createConnections({
+ createConnections({
organizationIntegrationId: organizationIntegration?.id,
connection: {
foreign_project_id: foreignProjectId,
@@ -257,12 +249,6 @@ const CreateProject = ({
},
orgSlug: selectedOrganization?.slug,
})
-
- setLoading(false)
-
- if (next) {
- window.location.href = next
- }
},
}
)