Skip to main content

Build a User Management App with Ionic React

还没翻译译自英文(supabase.com)本页 47 段都还没译

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

Note

If you get stuck while working through this guide, refer to the full example on GitHub.

Project setup

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. Create a new project in the Supabase Dashboard.
  2. Enter your project details.
  3. Wait for the new database to launch.

Set up the database schema

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.

DashboardSQL

  1. Go to the SQL Editor page in the Dashboard.
  2. Click User Management Starter under the Reference > Examples tab.
  3. Click Run.

Note

You can pull the database schema down to your local project by running the db pull command. Read the local development docs for detailed instructions.

supabase link --project-ref <project-id>
# You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>
supabase db pull

Get API details

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.

Project URL: https://<project-ref>.supabase.co (find yours in the dashboard)

Publishable key: sb_publishable_... (find yours in the dashboard)

Note

See API keys for a full explanation of all key types, their uses, and where to find them.

Building the app

Start building the React app from scratch.

Initialize an Ionic React app

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

Install the only additional dependency: supabase-js

npm install @supabase/supabase-js

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

.env

VITE_SUPABASE_URL=YOUR_SUPABASE_URL
VITE_SUPABASE_KEY=YOUR_SUPABASE_KEY

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.

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)

Set up a sign-in route

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.

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>
  )
}

Account page

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

Create a new component for that called 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>
  )
}

Launch!

Now that you have all the components in place, update 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

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

ionic serve

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

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 is a cross platform native runtime from Ionic that enables web apps to be deployed through the app store and provides access to native device API.

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

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

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>
)

Then create an AvatarComponent.

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>
  )
}

Add the new widget

And then add the widget to the Account page:

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>
  )
}

At this stage you have a fully functional application!