Skip to content

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

Update solidjs guide to use supabase v2 rc

Andrew Smithbb8b54e9148f
diff --git a/apps/reference/docs/guides/with-solidjs.mdx b/apps/reference/docs/guides/with-solidjs.mdx
index 931de124084..93395c57083 100644
--- a/apps/reference/docs/guides/with-solidjs.mdx
+++ b/apps/reference/docs/guides/with-solidjs.mdx
@@ -163,14 +163,14 @@ Let's start building the SolidJS app from scratch.
We can use [Degit](https://github.com/Rich-Harris/degit) to initialize an app called `supabase-solid`:
```bash
-npx degit solidjs/templates/js supabase-solid
+npx degit solidjs/templates/ts supabase-solid
cd supabase-solid
```
Then let's install the only additional dependency: [supabase-js](https://github.com/supabase/supabase-js)
```bash
-npm install @supabase/supabase-js
+npm install @supabase/supabase-js@rc
```
And finally we want to save the environment variables in a `.env`.
@@ -200,7 +200,7 @@ You can find the full contents of this file [here](https://raw.githubusercontent
Let's set up a SolidJS component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.
-```jsx title="/src/Auth.jsx"
+```jsx title="/src/Auth.tsx"
import { createSignal } from 'solid-js'
import { supabase } from './supabaseClient'
@@ -208,46 +208,46 @@ export default function Auth() {
const [loading, setLoading] = createSignal(false)
const [email, setEmail] = createSignal('')
- const handleLogin = async (e) => {
+ const handleLogin = async (e: SubmitEvent) => {
e.preventDefault()
try {
setLoading(true)
- const { error } = await supabase.auth.signIn({ email: email() })
+ const { error } = await supabase.auth.signInWithOtp({ email: email() })
if (error) throw error
alert('Check your email for the login link!')
} catch (error) {
- alert(error.error_description || error.message)
+ if (error instanceof Error) {
+ alert(error.message)
+ }
} finally {
setLoading(false)
}
}
return (
- <div className="row flex-center flex">
- <div className="col-6 form-widget" aria-live="polite">
- <h1 className="header">Supabase + SolidJS</h1>
- <p className="description">
- Sign in via magic link with your email below
- </p>
- {loading() ? (
- 'Sending magic link...'
- ) : (
- <form onSubmit={handleLogin}>
- <label htmlFor="email">Email</label>
+ <div class="row flex-center flex">
+ <div class="col-6 form-widget" aria-live="polite">
+ <h1 class="header">Supabase + SolidJS</h1>
+ <p class="description">Sign in via magic link with your email below</p>
+ <form class="form-widget" onSubmit={handleLogin}>
+ <div>
+ <label for="email">Email</label>
<input
id="email"
- className="inputField"
+ class="inputField"
type="email"
placeholder="Your email"
value={email()}
- onChange={(e) => setEmail(e.target.value)}
+ onChange={(e) => setEmail(e.currentTarget.value)}
/>
- <button type="submit" className="button block" aria-live="polite">
- Send magic link
+ </div>
+ <div>
+ <button type="submit" class="button block" aria-live="polite">
+ {loading() ? <span>Loading</span> : <span>Send magic link</span>}
</button>
- </form>
- )}
+ </div>
+ </form>
</div>
</div>
)
@@ -258,27 +258,31 @@ export default function Auth() {
After a user is signed in we can allow them to edit their profile details and manage their account.
-Let's create a new component for that called `Account.js`.
+Let's create a new component for that called `Account.tsx`.
-```jsx title="src/Account.jsx"
-import { createSignal, createEffect } from 'solid-js'
+```jsx title="src/Account.tsx"
+import { AuthSession } from '@supabase/supabase-js'
+import { Component, createEffect, createSignal } from 'solid-js'
import { supabase } from './supabaseClient'
-const Account = (props) => {
+interface Props {
+ session: AuthSession
+}
+
+const Account: Component<Props> = ({ session }) => {
const [loading, setLoading] = createSignal(true)
- const [username, setUsername] = createSignal(null)
- const [website, setWebsite] = createSignal(null)
- const [avatar_url, setAvatarUrl] = createSignal(null)
+ const [username, setUsername] = createSignal<string | null>(null)
+ const [website, setWebsite] = createSignal<string | null>(null)
+ const [avatarUrl, setAvatarUrl] = createSignal<string | null>(null)
createEffect(() => {
- props.session
getProfile()
})
const getProfile = async () => {
try {
setLoading(true)
- const user = supabase.auth.user()
+ const { user } = session
let { data, error, status } = await supabase
.from('profiles')
@@ -296,36 +300,38 @@ const Account = (props) => {
setAvatarUrl(data.avatar_url)
}
} catch (error) {
- alert(error.message)
+ if (error instanceof Error) {
+ alert(error.message)
+ }
} finally {
setLoading(false)
}
}
- const updateProfile = async (e) => {
+ const updateProfile = async (e: Event) => {
e.preventDefault()
try {
setLoading(true)
- const user = supabase.auth.user()
+ const { user } = session
const updates = {
id: user.id,
username: username(),
website: website(),
- avatar_url: avatar_url(),
- updated_at: new Date(),
+ avatar_url: avatarUrl(),
+ updated_at: new Date().toISOString(),
}
- let { error } = await supabase.from('profiles').upsert(updates, {
- returning: 'minimal', // Don't return the value after inserting
- })
+ let { error } = await supabase.from('profiles').upsert(updates)
if (error) {
throw error
}
} catch (error) {
- alert(error.message)
+ if (error instanceof Error) {
+ alert(error.message)
+ }
} finally {
setLoading(false)
}
@@ -333,47 +339,35 @@ const Account = (props) => {
return (
<div aria-live="polite">
- {loading() ? (
- 'Saving ...'
- ) : (
- <form onSubmit={updateProfile} className="form-widget">
- <div>Email: {props.session.user.email}</div>
- <div>
- <label htmlFor="username">Name</label>
- <input
- id="username"
- type="text"
- value={username() || ''}
- onChange={(e) => setUsername(e.target.value)}
- />
- </div>
- <div>
- <label htmlFor="website">Website</label>
- <input
- id="website"
- type="url"
- value={website() || ''}
- onChange={(e) => setWebsite(e.target.value)}
- />
- </div>
- <div>
- <button
- type="submit"
- className="button primary block"
- disabled={loading()}
- >
- Update profile
- </button>
- </div>
- </form>
- )}
- <button
- type="button"
- className="button block"
- onClick={() => supabase.auth.signOut()}
- >
- Sign Out
- </button>
+ <form onSubmit={updateProfile} class="form-widget">
+ <div>Email: {session.user.email}</div>
+ <div>
+ <label for="username">Name</label>
+ <input
+ id="username"
+ type="text"
+ value={username() || ''}
+ onChange={(e) => setUsername(e.currentTarget.value)}
+ />
+ </div>
+ <div>
+ <label for="website">Website</label>
+ <input
+ id="website"
+ type="text"
+ value={website() || ''}
+ onChange={(e) => setWebsite(e.currentTarget.value)}
+ />
+ </div>
+ <div>
+ <button type="submit" class="button primary block" disabled={loading()}>
+ {loading() ? 'Saving ...' : 'Update profile'}
+ </button>
+ </div>
+ <button type="button" class="button block" onClick={() => supabase.auth.signOut()}>
+ Sign Out
+ </button>
+ </form>
</div>
)
}
@@ -383,20 +377,22 @@ export default Account
### Launch!
-Now that we have all the components in place, let's update `App.js`:
+Now that we have all the components in place, let's update `App.tsx`:
-```jsx title="src/App.jsx"
-import './index.css'
-import { createSignal, createEffect } from 'solid-js'
+```jsx title="src/App.tsx"
+import { Component, createEffect, createSignal } from 'solid-js'
import { supabase } from './supabaseClient'
-import Auth from './Auth'
+import { AuthSession } from '@supabase/supabase-js'
import Account from './Account'
+import Auth from './Auth'
-export default () => {
- const [session, setSession] = createSignal(null)
+const App: Component = () => {
+ const [session, setSession] = createSignal<AuthSession | null>(null)
createEffect(() => {
- setSession(supabase.auth.session())
+ supabase.auth.getSession().then(({ data: { session } }) => {
+ setSession(session)
+ })
supabase.auth.onAuthStateChange((_event, session) => {
setSession(session)
@@ -404,15 +400,13 @@ export default () => {
})
return (
- <div className="container" style={{ padding: '50px 0 100px 0' }}>
- {!session() ? (
- <Auth />
- ) : (
- <Account key={session().user.id} session={session()} />
- )}
+ <div class="container" style={{ padding: '50px 0 100px 0' }}>
+ {!session() ? <Auth /> : <Account session={session()!} />}
</div>
)
}
+
+export default App
```
Once that's done, run this in a terminal window:
@@ -433,49 +427,54 @@ Every Supabase project is configured with [Storage](/docs/guides/storage) for ma
Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component:
-```jsx title="src/Avatar.jsx"
-import { createEffect, createSignal } from 'solid-js'
+```jsx title="src/Avatar.tsx"
+import { Component, createEffect, createSignal, JSX } from 'solid-js'
import { supabase } from './supabaseClient'
-export default (props) => {
- const [avatarUrl, setAvatarUrl] = createSignal(null)
+interface Props {
+ size: number
+ url: string | null
+ onUpload: (event: Event, filePath: string) => void
+}
+
+const Avatar: Component<Props> = (props) => {
+ const [avatarUrl, setAvatarUrl] = createSignal<string | null>(null)
const [uploading, setUploading] = createSignal(false)
createEffect(() => {
- if (props.url()) downloadImage(props.url())
+ if (props.url) downloadImage(props.url)
})
- const downloadImage = async (path) => {
+ const downloadImage = async (path: string) => {
try {
- const { data, error } = await supabase.storage
- .from('avatars')
- .download(path)
+ const { data, error } = await supabase.storage.from('avatars').download(path)
if (error) {
throw error
}
const url = URL.createObjectURL(data)
setAvatarUrl(url)
} catch (error) {
- console.log('Error downloading image: ', error.message)
+ if (error instanceof Error) {
+ console.log('Error downloading image: ', error.message)
+ }
}
}
- const uploadAvatar = async (event) => {
+ const uploadAvatar: JSX.EventHandler<HTMLInputElement, Event> = async (event) => {
try {
setUploading(true)
- if (!event.target.files || event.target.files.length === 0) {
+ const target = event.currentTarget
+ if (!target?.files || target.files.length === 0) {
throw new Error('You must select an image to upload.')
}
- const file = event.target.files[0]
+ const file = target.files[0]
const fileExt = file.name.split('.').pop()
const fileName = `${Math.random()}.${fileExt}`
const filePath = `${fileName}`
- let { error: uploadError } = await supabase.storage
- .from('avatars')
- .upload(filePath, file)
+ let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)
if (uploadError) {
throw uploadError
@@ -483,7 +482,9 @@ export default (props) => {
props.onUpload(event, filePath)
} catch (error) {
- alert(error.message)
+ if (error instanceof Error) {
+ alert(error.message)
+ }
} finally {
setUploading(false)
}
@@ -491,56 +492,57 @@ export default (props) => {
return (
<div style={{ width: props.size }} aria-live="polite">
- <img
- src={
- avatarUrl()
- ? avatarUrl()
- : `https://place-hold.it/${props.size}x${props.size}`
- }
- alt={avatarUrl() ? 'Avatar' : 'No image'}
- className="avatar image"
- style={{ height: props.size, width: props.size }}
- />
- {uploading() ? (
- 'Uploading...'
+ {avatarUrl() ? (
+ <img
+ src={avatarUrl()!}
+ alt={avatarUrl() ? 'Avatar' : 'No image'}
+ class="avatar image"
+ style={{ height: `${props.size}px`, width: `${props.size}px` }}
+ />
) : (
- <>
- <label className="button primary block" htmlFor="single">
- Upload an avatar
- </label>
- <span style="display:none">
- <input
- type="file"
- id="single"
- accept="image/*"
- onChange={uploadAvatar}
- disabled={uploading()}
- />
- </span>
- </>
+ <div
+ class="avatar no-image"
+ style={{ height: `${props.size}px`, width: `${props.size}px` }}
+ />
)}
+ <div style={{ width: `${props.size}px` }}>
+ <label class="button primary block" for="single">
+ {uploading() ? 'Uploading ...' : 'Upload avatar'}
+ </label>
+ <span style="display:none">
+ <input
+ type="file"
+ id="single"
+ accept="image/*"
+ onChange={uploadAvatar}
+ disabled={uploading()}
+ />
+ </span>
+ </div>
</div>
)
}
+
+export default Avatar
```
### Add the new widget
And then we can add the widget to the Account page:
-```jsx title="src/Account.jsx"
+```jsx title="src/Account.tsx"
// Import the new component
import Avatar from './Avatar'
// ...
return (
- <div className="form-widget">
+ <form onSubmit={updateProfile} class="form-widget">
{/* Add to the body */}
<Avatar
- url={avatar_url}
+ url={avatarUrl()}
size={150}
- onUpload={(e, url) => {
+ onUpload={(e: Event, url: string) => {
setAvatarUrl(url)
updateProfile(e)
}}