Skip to content

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

move useProfile to react-query

Alaister Young4852df732d7e
diff --git a/studio/data/profile/keys.ts b/studio/data/profile/keys.ts
new file mode 100644
index 00000000000..49ba29ad7b7
--- /dev/null
+++ b/studio/data/profile/keys.ts
@@ -0,0 +1,3 @@
+export const profileKeys = {
+ profile: () => ['profile'] as const,
+}
diff --git a/studio/data/profile/profile-query.ts b/studio/data/profile/profile-query.ts
new file mode 100644
index 00000000000..d48256ef0d3
--- /dev/null
+++ b/studio/data/profile/profile-query.ts
@@ -0,0 +1,52 @@
+import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
+import { get } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { useCallback } from 'react'
+import { profileKeys } from './keys'
+
+export type Profile = {
+ id: number
+ auth0_id: string
+ primary_email: string
+ username: string
+ first_name: string
+ last_name: string
+ mobile: string | null
+ is_alpha_user: boolean
+ gotrue_id: string
+ free_project_limit: number
+}
+
+export type ProfileResponse = Profile
+
+export async function getProfile(signal?: AbortSignal) {
+ const response = await get(`${API_URL}/profile`, {
+ signal,
+ })
+ if (response.error) {
+ throw response.error
+ }
+
+ return response as ProfileResponse
+}
+
+export type ProfileData = Awaited<ReturnType<typeof getProfile>>
+export type ProfileError = unknown
+
+export const useProfileQuery = <TData = ProfileData>({
+ enabled = true,
+ ...options
+}: UseQueryOptions<ProfileData, ProfileError, TData> = {}) =>
+ useQuery<ProfileData, ProfileError, TData>(
+ profileKeys.profile(),
+ ({ signal }) => getProfile(signal),
+ options
+ )
+
+export const useProfilePrefetch = () => {
+ const client = useQueryClient()
+
+ return useCallback(() => {
+ client.prefetchQuery(profileKeys.profile(), ({ signal }) => getProfile(signal))
+ }, [])
+}
diff --git a/studio/data/profile/profile-update-mutation.ts b/studio/data/profile/profile-update-mutation.ts
new file mode 100644
index 00000000000..b1b9ba67252
--- /dev/null
+++ b/studio/data/profile/profile-update-mutation.ts
@@ -0,0 +1,45 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { post } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { profileKeys } from './keys'
+
+export type ProfileUpdateVariables = {
+ firstName: string
+ lastName: string
+}
+
+export async function updateProfile({ firstName, lastName }: ProfileUpdateVariables) {
+ const response = await post(`${API_URL}/profile/update`, {
+ first_name: firstName,
+ last_name: lastName,
+ })
+ if (response.error) {
+ throw response.error
+ }
+
+ return response
+}
+
+type ProfileUpdateData = Awaited<ReturnType<typeof updateProfile>>
+
+export const useProfileUpdateMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<ProfileUpdateData, unknown, ProfileUpdateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<ProfileUpdateData, unknown, ProfileUpdateVariables>(
+ (vars) => updateProfile(vars),
+ {
+ async onSuccess(data, variables, context) {
+ await queryClient.invalidateQueries(profileKeys.profile())
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/hooks/misc/withAuth.tsx b/studio/hooks/misc/withAuth.tsx
index bd0bfc2e287..b0757765064 100644
--- a/studio/hooks/misc/withAuth.tsx
+++ b/studio/hooks/misc/withAuth.tsx
@@ -4,9 +4,10 @@ import { NextRouter, useRouter } from 'next/router'
import { getReturnToPath, STORAGE_KEY } from 'lib/gotrue'
import { IS_PLATFORM } from 'lib/constants'
-import { useProfile, useStore, usePermissions } from 'hooks'
+import { useStore, usePermissions } from 'hooks'
import Error500 from '../../pages/500'
import { NextPageWithLayout } from 'types'
+import { useProfileQuery } from 'data/profile/profile-query'
const PLATFORM_ONLY_PAGES = ['reports', 'settings']
@@ -28,14 +29,25 @@ export function withAuth<T>(
const redirectTo = options?.redirectTo ?? defaultRedirectTo(ref)
const redirectIfFound = options?.redirectIfFound
- const returning =
- app.projects.isInitialized && app.organizations.isInitialized ? 'minimal' : undefined
- const { profile, isLoading, error } = useProfile(returning)
+ const {
+ data: profile,
+ isLoading,
+ error,
+ } = useProfileQuery({
+ onSuccess(profile) {
+ ui.setProfile(profile)
+
+ if (!app.organizations.isInitialized) app.organizations.load()
+ if (!app.projects.isInitialized) app.projects.load()
+ mutatePermissions()
+ },
+ })
+
const {
permissions,
isLoading: isPermissionLoading,
mutate: mutatePermissions,
- } = usePermissions(profile, returning)
+ } = usePermissions(profile)
const isAccessingBlockedPage = !IS_PLATFORM && PLATFORM_ONLY_PAGES.includes(page)
const isRedirecting =
@@ -43,19 +55,6 @@ export function withAuth<T>(
checkRedirectTo(isLoading, router, profile, error, redirectTo, redirectIfFound)
useEffect(() => {
- // This should run before redirecting
- if (!isLoading) {
- if (!profile) {
- ui.setProfile(undefined)
- } else if (returning !== 'minimal') {
- ui.setProfile(profile)
-
- if (!app.organizations.isInitialized) app.organizations.load()
- if (!app.projects.isInitialized) app.projects.load()
- mutatePermissions()
- }
- }
-
if (!isPermissionLoading) {
ui.setPermissions(permissions)
}
@@ -64,7 +63,7 @@ export function withAuth<T>(
if (isRedirecting) {
router.push(redirectTo)
}
- }, [isLoading, isPermissionLoading, isRedirecting, profile, permissions])
+ }, [isLoading, isPermissionLoading, isRedirecting, permissions])
useEffect(() => {
if (!isLoading && router.isReady) {
diff --git a/studio/hooks/queries/index.ts b/studio/hooks/queries/index.ts
index f2ec3fe6594..0722767ed0e 100644
--- a/studio/hooks/queries/index.ts
+++ b/studio/hooks/queries/index.ts
@@ -3,7 +3,6 @@ export * from './useOrganizationDetail'
export * from './useOrganizationRoles'
export * from './useFreeProjectLimitCheck'
export * from './usePermissions'
-export * from './useProfile'
export * from './useProjectAuthConfig'
export * from './useProjectSettings'
export * from './useProjectSubscription'
diff --git a/studio/hooks/queries/useProfile.ts b/studio/hooks/queries/useProfile.ts
deleted file mode 100644
index b4f8f78d79f..00000000000
--- a/studio/hooks/queries/useProfile.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import useSWR, { mutate } from 'swr'
-import { get } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
-import { User } from 'types'
-
-export function useProfile(returning?: 'minimal') {
- let url = `${API_URL}/profile`
-
- if (returning) {
- const query = new URLSearchParams({ returning }).toString()
- url = `${url}?${query}`
- }
-
- const { data, error } = useSWR<any>(url, get, { loadingTimeout: 10000 })
- const anyError = data?.error || error
-
- function mutateProfile(updatedUser: User, revalidate?: boolean) {
- mutate(
- url,
- {
- first_name: updatedUser.first_name,
- last_name: updatedUser.last_name,
- },
- revalidate ?? true
- )
- }
-
- return {
- profile: anyError ? undefined : data,
- isLoading: !anyError && !data,
- isError: !!anyError,
- error: anyError,
- mutateProfile,
- }
-}
diff --git a/studio/pages/account/me.tsx b/studio/pages/account/me.tsx
index 9b3cbad9551..e5cdeeeb8bd 100644
--- a/studio/pages/account/me.tsx
+++ b/studio/pages/account/me.tsx
@@ -1,17 +1,16 @@
import { observer } from 'mobx-react-lite'
import { useEffect, useState } from 'react'
-import { Button, IconArrowRight, IconMoon, IconSun, Input, Listbox } from 'ui'
+import { Button, IconMoon, IconSun, Input, Listbox } from 'ui'
import { Session } from '@supabase/supabase-js'
import { AccountLayout } from 'components/layouts'
import SchemaFormPanel from 'components/to-be-cleaned/forms/SchemaFormPanel'
import Panel from 'components/ui/Panel'
-import { useProfile, useStore } from 'hooks'
-import { post } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
+import { useProfileUpdateMutation } from 'data/profile/profile-update-mutation'
+import { useStore } from 'hooks'
import { auth } from 'lib/gotrue'
-import { NextPageWithLayout } from 'types'
import Link from 'next/link'
+import { NextPageWithLayout } from 'types'
const User: NextPageWithLayout = () => {
return (
@@ -39,14 +38,16 @@ export default User
const ProfileCard = observer(() => {
const { ui } = useStore()
- const { mutateProfile } = useProfile()
+ const { mutate } = useProfileUpdateMutation()
const user = ui.profile
const updateUser = async (model: any) => {
try {
- const updatedUser = await post(`${API_URL}/profile/update`, model)
- mutateProfile(updatedUser, false)
- ui.setProfile(updatedUser)
+ mutate({
+ firstName: model.first_name,
+ lastName: model.last_name,
+ })
+
ui.setNotification({ category: 'success', message: 'Successfully saved profile' })
} catch (error) {
ui.setNotification({
diff --git a/studio/pages/join/index.tsx b/studio/pages/join/index.tsx
index be1c151a700..120db3cb51b 100644
--- a/studio/pages/join/index.tsx
+++ b/studio/pages/join/index.tsx
@@ -3,10 +3,11 @@ import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import { Button, IconCheckSquare, Loading } from 'ui'
-import { useProfile, useStore } from 'hooks'
+import { useStore } from 'hooks'
import { auth } from 'lib/gotrue'
import { API_URL } from 'lib/constants'
import { get, post, delete_ } from 'lib/common/fetch'
+import { useProfileQuery } from 'data/profile/profile-query'
interface ITokenInfo {
organization_name?: string | undefined
@@ -23,7 +24,7 @@ const JoinOrganizationPage = () => {
const router = useRouter()
const { slug, token, name } = router.query
const { ui, app } = useStore()
- const { profile } = useProfile()
+ const { data: profile } = useProfileQuery()
const [isSubmitting, setIsSubmitting] = useState(false)
const [error, setError] = useState(false)
diff --git a/studio/types/base.ts b/studio/types/base.ts
index c86d136afe7..83a36b88918 100644
--- a/studio/types/base.ts
+++ b/studio/types/base.ts
@@ -41,7 +41,7 @@ export interface Project extends ProjectBase {
export interface User {
id: number
- mobile: string
+ mobile: string | null
primary_email: string
username: string
first_name: string