Skip to content
Getting Started

用 Ionic React 构建一个用户管理应用

本教程演示了如何构建一个基本的用户管理应用。该应用可以进行用户认证和识别,将用户的个人资料信息存储在数据库中,并允许用户登录、更新他们的个人资料信息以及上传头像。该应用使用了:

🌐 This tutorial demonstrates how to build a basic user management app. The app authenticates and identifies the user, stores their profile information in the database, and allows the user to log in, update their profile details, and upload a profile photo. The app uses:

Supabase User Management example

项目设置 #

🌐 Project setup

在你开始构建之前,你需要先设置数据库和 API。你可以通过在 Supabase 中启动一个新项目,然后在数据库中创建一个“架构”来完成这一步。

🌐 Before you start building you need to set up the Database and API. You can do this by starting a new Project in Supabase and then creating a "schema" inside the database.

创建一个项目 #

🌐 Create a project

  1. 在 Supabase 仪表板中创建一个新项目。
  2. 输入你的项目详情。
  3. 等新数据库上线。

设置数据库模式 #

🌐 Set up the database schema

现在设置数据库模式。你可以在 SQL 编辑器中使用“用户管理入门”快速开始,也可以复制粘贴下面的 SQL 并运行。

🌐 Now set up the database schema. You can use the "User Management Starter" quickstart in the SQL Editor, or you can copy/paste the SQL from below and run it.

  1. 在仪表板中转到SQL 编辑器页面。
  2. 在 参考 > 示例 选项卡下点击 用户管理入门。
  3. 点击运行。

获取 API 详情 #

🌐 Get API details

要与数据库表中的数据进行交互,你可以使用封装了自动生成的数据 API 端点的客户端库,并使用来自项目 Connect 对话框的项目 URL 和密钥进行认证。

🌐 To interact with data in database tables, you use the client libraries that wrap the auto-generated Data API endpoints, authenticating using the Project URL and key from the project Connect dialog.

正在构建应用 #

🌐 Building the app

从零开始搭建 React 应用。

🌐 Start building the React app from scratch.

初始化一个 Ionic React 应用 #

🌐 Initialize an Ionic React app

使用 Ionic CLI 来初始化一个叫做 supabase-ionic-react 的应用:

🌐 Use the Ionic CLI to initialize an app called supabase-ionic-react:

npm install -g @ionic/cli
ionic start supabase-ionic-react blank --type react
cd supabase-ionic-react

安装唯一的额外依赖: supabase-js

🌐 Install the only additional dependency: supabase-js

npm install @supabase/supabase-js

将环境变量保存在 .env 中。你需要之前复制的 API URL 和密钥 earlier。

🌐 Save the environment variables in a .env. You need the API URL and the key that you copied earlier.

VITE_SUPABASE_URL=YOUR_SUPABASE_URL
VITE_SUPABASE_KEY=YOUR_SUPABASE_KEY

在设置好 API 凭证后,创建一个辅助文件来初始化 Supabase 客户端。这些变量会在浏览器中暴露,这是安全的,因为它们使用的是受限的可发布密钥,而且 SQL 快速入门在 profiles 表上启用了 行级安全。

🌐 With the API credentials in place, create a helper file to initialize the Supabase client. These variables will be exposed in the browser, which is safe because they use a restricted publishable key and the SQL quickstart enables Row Level Security on the profiles table.

src/supabaseClient.ts
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY
if (!supabaseUrl || !supabasePublishableKey) {
throw new Error(
'Missing Supabase environment variables: VITE_SUPABASE_URL and VITE_SUPABASE_PUBLISHABLE_KEY must be set.'
)
}
export const supabase = createClient(supabaseUrl, supabasePublishableKey)
View source

设置一个登录路径 #

🌐 Set up a sign-in route

设置一个 React 组件来管理登录和注册,它使用魔法链接,让用户可以用邮箱登录而不用密码。

🌐 Set up a React component to manage sign-ins and sign-ups which uses Magic Links, so users can sign in with their email without using passwords.

src/pages/Login.tsx
import { useState } from 'react'
import type React from 'react'
import {
IonButton,
IonContent,
IonHeader,
IonInput,
IonItem,
IonList,
IonPage,
IonTitle,
IonToolbar,
useIonToast,
useIonLoading,
} from '@ionic/react'
import { supabase } from '../supabaseClient'
export function LoginPage() {
const [email, setEmail] = useState('')
const [showLoading, hideLoading] = useIonLoading()
const [showToast] = useIonToast()
const handleLogin = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
await showLoading()
try {
const { error } = await supabase.auth.signInWithOtp({ email })
if (error) throw error
await showToast({ message: 'Check your email for the login link!' })
} catch (e: any) {
await showToast({ message: e.error_description || e.message, duration: 5000 })
} finally {
await hideLoading()
}
}
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Login</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
<div className="ion-padding">
<h1>Supabase + Ionic React</h1>
<p>Sign in via magic link with your email below</p>
</div>
<IonList inset={true}>
<form onSubmit={handleLogin}>
<IonItem>
<IonInput
value={email}
name="email"
onIonInput={(e) => setEmail(e.detail.value ?? '')}
type="email"
label="Email"
labelPlacement="stacked"
></IonInput>
</IonItem>
<div className="ion-text-center">
<IonButton type="submit" fill="clear">
Login
</IonButton>
</div>
</form>
</IonList>
</IonContent>
</IonPage>
)
}
View source

账户页面 #

🌐 Account page

用户登录后,应能够编辑他们的个人资料信息并管理他们的账户。

🌐 After a user signs in, they should be able to edit their profile details and manage their account.

为此创建一个名为 Account.tsx 的新组件。

🌐 Create a new component for that called Account.tsx.

src/pages/Account.tsx
import {
IonButton,
IonContent,
IonHeader,
IonInput,
IonItem,
IonLabel,
IonPage,
IonTitle,
IonToolbar,
useIonLoading,
useIonToast,
useIonRouter,
} from '@ionic/react'
import { useEffect, useState } from 'react'
// ...
import { supabase } from '../supabaseClient'
export function AccountPage() {
const [showLoading, hideLoading] = useIonLoading()
const [showToast] = useIonToast()
const router = useIonRouter()
const [email, setEmail] = useState('')
const [profile, setProfile] = useState({
username: '',
website: '',
avatar_url: '',
})
useEffect(() => {
getProfile()
}, [])
const getProfile = async () => {
await showLoading()
try {
const { data: authData } = await supabase.auth.getClaims()
if (!authData?.claims) throw new Error('No user logged in')
const { claims } = authData
setEmail(claims.email as string)
const { data, error, status } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', claims.sub)
.single()
if (error && status !== 406) {
throw error
}
if (data) {
setProfile({
username: data.username,
website: data.website,
avatar_url: data.avatar_url,
})
}
} catch (error: any) {
showToast({ message: error.message, duration: 5000 })
} finally {
await hideLoading()
}
}
const signOut = async () => {
await supabase.auth.signOut()
router.push('/', 'forward', 'replace')
}
const updateProfile = async (e?: any, avatar_url?: string) => {
e?.preventDefault()
await showLoading()
try {
const { data } = await supabase.auth.getClaims()
if (!data?.claims) throw new Error('No user logged in')
const { claims } = data
const updates = {
id: claims.sub,
...profile,
...(avatar_url !== undefined ? { avatar_url } : {}),
updated_at: new Date(),
}
const { error } = await supabase.from('profiles').upsert(updates)
if (error) {
throw error
}
// Ensure local profile state reflects the updated avatar URL
if (avatar_url !== undefined) {
setProfile((prev) => ({
...prev,
avatar_url,
}))
}
if (avatar_url !== undefined) {
setProfile((current) => ({
...current,
avatar_url,
}))
}
} catch (error: any) {
showToast({ message: error.message, duration: 5000 })
} finally {
await hideLoading()
}
}
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Account</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
{/* ... */}
<form onSubmit={updateProfile}>
<IonItem>
<IonLabel>
<p>Email</p>
<p>{email}</p>
</IonLabel>
</IonItem>
<IonItem>
<IonInput
type="text"
name="username"
value={profile.username}
onIonInput={(e) => setProfile({ ...profile, username: e.detail.value ?? '' })}
label="Name"
labelPlacement="stacked"
></IonInput>
</IonItem>
<IonItem>
<IonInput
type="url"
name="website"
value={profile.website}
onIonInput={(e) => setProfile({ ...profile, website: e.detail.value ?? '' })}
label="Website"
labelPlacement="stacked"
></IonInput>
</IonItem>
<div className="ion-text-center">
<IonButton fill="clear" type="submit">
Update Profile
</IonButton>
</div>
</form>
<div className="ion-text-center">
<IonButton fill="clear" onClick={signOut}>
Log Out
</IonButton>
</div>
</IonContent>
</IonPage>
)
}
View source

触发! #

🌐 Launch!

现在你已经准备好所有组件了,更新一下 App.tsx :

🌐 Now that you have all the components in place, update App.tsx:

src/App.tsx
import { Redirect, Route } from 'react-router-dom'
import { IonApp, IonRouterOutlet, setupIonicReact } from '@ionic/react'
import { IonReactRouter } from '@ionic/react-router'
import { supabase } from './supabaseClient'
import '@ionic/react/css/ionic.bundle.css'
/* Theme variables */
import './theme/variables.css'
import { LoginPage } from './pages/Login'
import { AccountPage } from './pages/Account'
import { useEffect, useState } from 'react'
import type { FC } from 'react'
setupIonicReact()
const App: FC = () => {
const [claims, setClaims] = useState<any>(null)
useEffect(() => {
supabase.auth.getClaims().then(({ data }) => {
if (data) {
setClaims(data.claims)
}
})
const {
data: { subscription },
} = supabase.auth.onAuthStateChange(() => {
supabase.auth.getClaims().then(({ data }) => {
if (data) {
setClaims(data.claims)
}
})
})
return () => subscription.unsubscribe()
}, [])
return (
<IonApp>
<IonReactRouter>
<IonRouterOutlet>
<Route
exact
path="/"
render={() => {
return claims ? <Redirect to="/account" /> : <LoginPage />
}}
/>
<Route
exact
path="/account"
render={() => (claims ? <AccountPage /> : <Redirect to="/" />)}
/>
</IonRouterOutlet>
</IonReactRouter>
</IonApp>
)
}
export default App
View source

完成后,在终端窗口运行这个:

🌐 Once that's done, run this in a terminal window:

ionic serve

然后在浏览器中打开 ionic serve 打印的 URL(默认是 http://localhost:8100),你就应该能看到完整的应用了。

🌐 Then open your browser to the URL printed by ionic serve (by default, http://localhost:8100) and you should see the completed app.

Supabase Ionic React

额外奖励:头像 #

🌐 Bonus: Profile photos

每个 Supabase 项目都配置了 Storage 来管理像照片和视频这样的大文件。

🌐 Every Supabase project is configured with Storage for managing large files like photos and videos.

创建一个上传小工具 #

🌐 Create an upload widget

首先安装两个软件包,以便与用户的相机互动。

🌐 First install two packages in order to interact with the user's camera.

npm install @ionic/pwa-elements @capacitor/camera

Capacitor 是 Ionic 提供的一个跨平台原生运行时,它可以让网页应用通过应用商店发布,并提供对原生设备 API 的访问。

Ionic PWA 元素是一个配套包,它会为某些没有用户界面的浏览器 API 提供自定义的 Ionic UI 填充。

🌐 Ionic PWA elements is a companion package that will polyfill certain browser APIs that provide no user interface with custom Ionic UI.

在安装了那些包之后,更新 index.tsx 以包含针对 Ionic PWA Elements 的额外引导调用。

🌐 With those packages installed update index.tsx to include an additional bootstrapping call for the Ionic PWA Elements.

src/index.tsx
import React from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
import { defineCustomElements } from '@ionic/pwa-elements/loader'
defineCustomElements(window)
const container = document.getElementById('root')
const root = createRoot(container!)
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
)
View source

然后创建一个 AvatarComponent。

🌐 Then create an AvatarComponent.

src/components/Avatar.tsx
import { IonIcon } from '@ionic/react'
import { person } from 'ionicons/icons'
import { Camera, CameraResultType } from '@capacitor/camera'
import { useEffect, useState } from 'react'
import { supabase } from '../supabaseClient'
import './Avatar.css'
export function Avatar({
url,
onUpload,
}: {
url: string
onUpload: (file: string) => Promise<void>
}) {
const [avatarUrl, setAvatarUrl] = useState<string | undefined>()
useEffect(() => {
if (url) {
downloadImage(url)
}
}, [url])
const uploadAvatar = async () => {
try {
const photo = await Camera.getPhoto({
resultType: CameraResultType.DataUrl,
})
const file = await fetch(photo.dataUrl!)
.then((res) => res.blob())
.then((blob) => new File([blob], 'my-file', { type: `image/${photo.format}` }))
const fileName = `${Math.random()}-${new Date().getTime()}.${photo.format}`
const { error: uploadError } = await supabase.storage.from('avatars').upload(fileName, file)
if (uploadError) {
throw uploadError
}
await onUpload(fileName)
} catch (error) {
console.log(error)
}
}
const downloadImage = async (path: string) => {
try {
const { data, error } = await supabase.storage.from('avatars').download(path)
if (error) {
throw error
}
const url = URL.createObjectURL(data)
setAvatarUrl(url)
} catch (error: any) {
console.log('Error downloading image: ', error.message)
}
}
useEffect(() => {
return () => {
if (avatarUrl) {
URL.revokeObjectURL(avatarUrl)
}
}
}, [avatarUrl])
return (
<div className="avatar">
<button type="button" className="avatar_wrapper" onClick={uploadAvatar}>
{avatarUrl ? (
<img src={avatarUrl} alt="User avatar" />
) : (
<IonIcon icon={person} className="no-avatar" />
)}
</button>
</div>
)
}
View source

添加新小部件 #

🌐 Add the new widget

然后把小部件添加到账户页面上:

🌐 And then add the widget to the Account page:

src/pages/Account.tsx
import {
IonButton,
IonContent,
IonHeader,
IonInput,
IonItem,
IonLabel,
IonPage,
IonTitle,
IonToolbar,
useIonLoading,
useIonToast,
useIonRouter,
} from '@ionic/react'
import { useEffect, useState } from 'react'
import { Avatar } from '../components/Avatar'
import { supabase } from '../supabaseClient'
export function AccountPage() {
const [showLoading, hideLoading] = useIonLoading()
const [showToast] = useIonToast()
const router = useIonRouter()
const [email, setEmail] = useState('')
const [profile, setProfile] = useState({
username: '',
website: '',
avatar_url: '',
})
useEffect(() => {
getProfile()
}, [])
const getProfile = async () => {
await showLoading()
try {
const { data: authData } = await supabase.auth.getClaims()
if (!authData?.claims) throw new Error('No user logged in')
const { claims } = authData
setEmail(claims.email as string)
const { data, error, status } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', claims.sub)
.single()
if (error && status !== 406) {
throw error
}
if (data) {
setProfile({
username: data.username,
website: data.website,
avatar_url: data.avatar_url,
})
}
} catch (error: any) {
showToast({ message: error.message, duration: 5000 })
} finally {
await hideLoading()
}
}
const signOut = async () => {
await supabase.auth.signOut()
router.push('/', 'forward', 'replace')
}
const updateProfile = async (e?: any, avatar_url?: string) => {
e?.preventDefault()
await showLoading()
try {
const { data } = await supabase.auth.getClaims()
if (!data?.claims) throw new Error('No user logged in')
const { claims } = data
const updates = {
id: claims.sub,
...profile,
...(avatar_url !== undefined ? { avatar_url } : {}),
updated_at: new Date(),
}
const { error } = await supabase.from('profiles').upsert(updates)
if (error) {
throw error
}
// Ensure local profile state reflects the updated avatar URL
if (avatar_url !== undefined) {
setProfile((prev) => ({
...prev,
avatar_url,
}))
}
if (avatar_url !== undefined) {
setProfile((current) => ({
...current,
avatar_url,
}))
}
} catch (error: any) {
showToast({ message: error.message, duration: 5000 })
} finally {
await hideLoading()
}
}
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Account</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
<Avatar
url={profile.avatar_url}
onUpload={(fileName) => updateProfile(undefined, fileName)}
></Avatar>
<form onSubmit={updateProfile}>
<IonItem>
<IonLabel>
<p>Email</p>
<p>{email}</p>
</IonLabel>
</IonItem>
<IonItem>
<IonInput
type="text"
name="username"
value={profile.username}
onIonInput={(e) => setProfile({ ...profile, username: e.detail.value ?? '' })}
label="Name"
labelPlacement="stacked"
></IonInput>
</IonItem>
<IonItem>
<IonInput
type="url"
name="website"
value={profile.website}
onIonInput={(e) => setProfile({ ...profile, website: e.detail.value ?? '' })}
label="Website"
labelPlacement="stacked"
></IonInput>
</IonItem>
<div className="ion-text-center">
<IonButton fill="clear" type="submit">
Update Profile
</IonButton>
</div>
</form>
<div className="ion-text-center">
<IonButton fill="clear" onClick={signOut}>
Log Out
</IonButton>
</div>
</IonContent>
</IonPage>
)
}
View source

在这个阶段,你已经有了一个完全可用的应用!

🌐 At this stage you have a fully functional application!