Skip to content

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

Update documentation to use Vite

Andrew Smith3aa2124cc556
diff --git a/apps/docs/pages/guides/getting-started/quickstarts/reactjs.mdx b/apps/docs/pages/guides/getting-started/quickstarts/reactjs.mdx
index ea117046949..02422ea1927 100644
--- a/apps/docs/pages/guides/getting-started/quickstarts/reactjs.mdx
+++ b/apps/docs/pages/guides/getting-started/quickstarts/reactjs.mdx
@@ -24,8 +24,8 @@ export const meta = {
```sql SQL_EDITOR
-- Create the table
CREATE TABLE countries (
- id SERIAL PRIMARY KEY,
- name VARCHAR(255) NOT NULL
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
);
-- Insert some sample data into the table
INSERT INTO countries (name) VALUES ('United States');
@@ -41,14 +41,14 @@ export const meta = {
<StepHikeCompact.Details title="Create a React app">
- Create a React app using the `create-react-app` command.
+ Create a React app using a [Vite](https://vitejs.dev/guide/) template.
</StepHikeCompact.Details>
<StepHikeCompact.Code>
```bash Terminal
- npx create-react-app my-app
+ npm create vite@latest my-app -- --template react
```
</StepHikeCompact.Code>
@@ -77,25 +77,42 @@ export const meta = {
<StepHikeCompact.Step step={4}>
<StepHikeCompact.Details title="Query data from the app">
- In `index.js`, create a Supabase client using your [Project URL and public API (anon) key](https://app.supabase.com/project/_/settings/api).
+ In `App.jsx`, create a Supabase client using your [Project URL and public API (anon) key](https://app.supabase.com/project/_/settings/api).
- Add a `getCountries` function to fetch the data and log the query result to the browser console.
+ Add a `getCountries` function to fetch the data and display the query result to the page.
</StepHikeCompact.Details>
<StepHikeCompact.Code>
- ```js src/index.js
- import { createClient } from '@supabase/supabase-js'
+ ```js src/App.jsx
+ import { useEffect, useState } from "react";
+ import { createClient } from "@supabase/supabase-js";
- const supabase = createClient('https://<project>.supabase.co', '<your-anon-key>')
+ const supabase = createClient("https://<project>.supabase.co", "<your-anon-key>");
- async function getCountries() {
- const countries = await supabase.from('countries').select()
- console.log(countries)
+ function App() {
+ const [countries, setCountries] = useState([]);
+
+ useEffect(() => {
+ getCountries();
+ }, []);
+
+ async function getCountries() {
+ const { data } = await supabase.from("countries").select();
+ setCountries(data);
+ }
+
+ return (
+ <ul>
+ {countries.map((country) => (
+ <li key={country.name}>{country.name}</li>
+ ))}
+ </ul>
+ );
}
- getCountries()
+ export default App;
```
</StepHikeCompact.Code>
@@ -105,14 +122,14 @@ export const meta = {
<StepHikeCompact.Step step={5}>
<StepHikeCompact.Details title="Start the app">
- Start the app, go to http://localhost:3000 in a browser, and open the browser console and you should see the list of countries.
+ Start the app, go to http://localhost:5173 in a browser, and open the browser console and you should see the list of countries.
</StepHikeCompact.Details>
<StepHikeCompact.Code>
```bash Terminal
- npm start
+ npm run dev
```
</StepHikeCompact.Code>
diff --git a/apps/docs/pages/guides/getting-started/tutorials/with-react.mdx b/apps/docs/pages/guides/getting-started/tutorials/with-react.mdx
index 73c30cd56cb..b72fa02a445 100644
--- a/apps/docs/pages/guides/getting-started/tutorials/with-react.mdx
+++ b/apps/docs/pages/guides/getting-started/tutorials/with-react.mdx
@@ -22,11 +22,11 @@ Let's start building the React app from scratch.
### Initialize a React app
-We can use [Create React App](https://create-react-app.dev/docs/getting-started/) to initialize
+We can use [Vite](https://vitejs.dev/guide/) to initialize
an app called `supabase-react`:
```bash
-npx create-react-app supabase-react
+npm create vite@latest supabase-react -- --template react
cd supabase-react
```
@@ -40,8 +40,8 @@ And finally we want to save the environment variables in a `.env.local` file.
All we need are the API URL and the `anon` key that you copied [earlier](#get-the-api-keys).
```bash title=.env
-REACT_APP_SUPABASE_URL=YOUR_SUPABASE_URL
-REACT_APP_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
+VITE_SUPABASE_URL=YOUR_SUPABASE_URL
+VITE_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
```
Now that we have the API credentials in place, let's create a helper file to initialize the Supabase client. These variables will be exposed
@@ -52,8 +52,8 @@ Create and edit `src/supabaseClient.js`:
```js title=src/supabaseClient.js
import { createClient } from '@supabase/supabase-js'
-const supabaseUrl = process.env.REACT_APP_SUPABASE_URL
-const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY
+const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
+const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
export const supabase = createClient(supabaseUrl, supabaseAnonKey)
```
@@ -65,9 +65,9 @@ You can find the full contents of this file [here](https://raw.githubusercontent
Let's set up a React component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.
-Create and edit `src/Auth.js`:
+Create and edit `src/Auth.jsx`:
-```jsx title=src/Auth.js
+```jsx title=src/Auth.jsx
import { useState } from 'react'
import { supabase } from './supabaseClient'
@@ -75,44 +75,42 @@ export default function Auth() {
const [loading, setLoading] = useState(false)
const [email, setEmail] = useState('')
- const handleLogin = async (e) => {
- e.preventDefault()
+ const handleLogin = async (event) => {
+ event.preventDefault()
- try {
- setLoading(true)
- const { error } = await supabase.auth.signInWithOtp({ email })
- if (error) throw error
- alert('Check your email for the login link!')
- } catch (error) {
+ setLoading(true)
+ const { error } = await supabase.auth.signInWithOtp({ email })
+
+ if (error) {
alert(error.error_description || error.message)
- } finally {
- setLoading(false)
+ } else {
+ alert('Check your email for the login link!')
}
+ setLoading(false)
}
return (
- <div className="row flex-center flex">
- <div className="col-6 form-widget" aria-live="polite">
+ <div className="row flex flex-center">
+ <div className="col-6 form-widget">
<h1 className="header">Supabase + React</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>
+ <form className="form-widget" onSubmit={handleLogin}>
+ <div>
<input
- id="email"
className="inputField"
type="email"
placeholder="Your email"
value={email}
+ required={true}
onChange={(e) => setEmail(e.target.value)}
/>
- <button className="button block" aria-live="polite">
- Send magic link
+ </div>
+ <div>
+ <button className={'button block'} disabled={loading}>
+ {loading ? <span>Loading</span> : <span>Send magic link</span>}
</button>
- </form>
- )}
+ </div>
+ </form>
</div>
</div>
)
@@ -123,130 +121,119 @@ 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 `src/Account.js`.
+Let's create a new component for that called `src/Account.jsx`.
-```jsx title=src/Account.js
+```jsx title=src/Account.jsx
import { useState, useEffect } from 'react'
import { supabase } from './supabaseClient'
-const Account = ({ session }) => {
+export default function Account({ session }) {
const [loading, setLoading] = useState(true)
const [username, setUsername] = useState(null)
const [website, setWebsite] = useState(null)
const [avatar_url, setAvatarUrl] = useState(null)
useEffect(() => {
- getProfile()
- }, [session])
-
- const getProfile = async () => {
- try {
+ async function getProfile() {
setLoading(true)
const { user } = session
- let { data, error, status } = await supabase
+ let { data, error } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', user.id)
.single()
- if (error && status !== 406) {
- throw error
- }
-
- if (data) {
+ if (error) {
+ console.warn(error)
+ } else if (data) {
setUsername(data.username)
setWebsite(data.website)
setAvatarUrl(data.avatar_url)
}
- } catch (error) {
- alert(error.message)
- } finally {
+
setLoading(false)
}
- }
- const updateProfile = async (e) => {
- e.preventDefault()
+ getProfile()
+ }, [session])
- try {
- setLoading(true)
- const { user } = session
+ async function updateProfile(event) {
+ event.preventDefault()
- const updates = {
- id: user.id,
- username,
- website,
- avatar_url,
- updated_at: new Date(),
- }
+ setLoading(true)
+ const { user } = session
- let { error } = await supabase.from('profiles').upsert(updates)
+ const updates = {
+ id: user.id,
+ username,
+ website,
+ avatar_url,
+ updated_at: new Date(),
+ }
- if (error) {
- throw error
- }
- } catch (error) {
+ let { error } = await supabase.from('profiles').upsert(updates)
+
+ if (error) {
alert(error.message)
- } finally {
- setLoading(false)
}
+ setLoading(false)
}
return (
- <div aria-live="polite">
- {loading ? (
- 'Saving ...'
- ) : (
- <form onSubmit={updateProfile} className="form-widget">
- <div>Email: {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 className="button primary block" disabled={loading}>
- Update profile
- </button>
- </div>
- </form>
- )}
- <button type="button" className="button block" onClick={() => supabase.auth.signOut()}>
- Sign Out
- </button>
- </div>
+ <form onSubmit={updateProfile} className="form-widget">
+ <div>
+ <label htmlFor="email">Email</label>
+ <input id="email" type="text" value={session.user.email} disabled />
+ </div>
+ <div>
+ <label htmlFor="username">Name</label>
+ <input
+ id="username"
+ type="text"
+ required
+ value={username || ''}
+ onChange={(e) => setUsername(e.target.value)}
+ />
+ </div>
+ <div>
+ <label htmlFor="website">Website</label>
+ <input
+ id="website"
+ type="website"
+ value={website || ''}
+ onChange={(e) => setWebsite(e.target.value)}
+ />
+ </div>
+
+ <div>
+ <button className="button block primary" type="submit" disabled={loading}>
+ {loading ? 'Loading ...' : 'Update'}
+ </button>
+ </div>
+
+ <div>
+ <button className="button block" type="button" onClick={() => supabase.auth.signOut()}>
+ Sign Out
+ </button>
+ </div>
+ </form>
)
}
-
-export default Account
```
### Launch!
-Now that we have all the components in place, let's update `src/App.js`:
+Now that we have all the components in place, let's update `src/App.jsx`:
-```jsx title=src/App.js
-import './index.css'
+```jsx title=src/App.jsx
+import './App.css'
import { useState, useEffect } from 'react'
import { supabase } from './supabaseClient'
import Auth from './Auth'
import Account from './Account'
-export default function App() {
+function App() {
const [session, setSession] = useState(null)
useEffect(() => {
@@ -265,15 +252,17 @@ export default function App() {
</div>
)
}
+
+export default App
```
Once that's done, run this in a terminal window:
```bash
-npm start
+npm run dev
```
-And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.
+And then open the browser to [localhost:5173](http://localhost:5173) and you should see the completed app.
![Supabase React](/docs/img/supabase-react-demo.png)
@@ -285,9 +274,9 @@ 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:
-Create and edit `src/Avatar.js`:
+Create and edit `src/Avatar.jsx`:
-```jsx title=src/Avatar.js
+```jsx title=src/Avatar.jsx
import { useEffect, useState } from 'react'
import { supabase } from './supabaseClient'
@@ -299,7 +288,7 @@ export default function Avatar({ url, size, onUpload }) {
if (url) downloadImage(url)
}, [url])
- const downloadImage = async (path) => {
+ async function downloadImage(path) {
try {
const { data, error } = await supabase.storage.from('avatars').download(path)
if (error) {
@@ -312,7 +301,7 @@ export default function Avatar({ url, size, onUpload }) {
}
}
- const uploadAvatar = async (event) => {
+ async function uploadAvatar(event) {
try {
setUploading(true)
@@ -331,7 +320,7 @@ export default function Avatar({ url, size, onUpload }) {
throw uploadError
}
- onUpload(filePath)
+ onUpload(event, filePath)
} catch (error) {
alert(error.message)
} finally {
@@ -340,31 +329,33 @@ export default function Avatar({ url, size, onUpload }) {
}
return (
- <div style={{ width: size }} aria-live="polite">
- <img
- src={avatarUrl ? avatarUrl : `https://place-hold.it/${size}x${size}`}
- alt={avatarUrl ? 'Avatar' : 'No image'}
- className="avatar image"
- style={{ height: size, width: size }}
- />
- {uploading ? (
- 'Uploading...'
+ <div>
+ {avatarUrl ? (
+ <img
+ src={avatarUrl}
+ alt="Avatar"
+ className="avatar image"
+ style={{ height: size, width: size }}
+ />
) : (
- <>
- <label className="button primary block" htmlFor="single">
- Upload an avatar
- </label>
- <div className="visually-hidden">
- <input
- type="file"
- id="single"
- accept="image/*"
- onChange={uploadAvatar}
- disabled={uploading}
- />
- </div>
- </>
+ <div className="avatar no-image" style={{ height: size, width: size }} />
)}
+ <div style={{ width: size }}>
+ <label className="button primary block" htmlFor="single">
+ {uploading ? 'Uploading ...' : 'Upload'}
+ </label>
+ <input
+ style={{
+ visibility: 'hidden',
+ position: 'absolute',
+ }}
+ type="file"
+ id="single"
+ accept="image/*"
+ onChange={uploadAvatar}
+ disabled={uploading}
+ />
+ </div>
</div>
)
}
@@ -372,9 +363,9 @@ export default function Avatar({ url, size, onUpload }) {
### Add the new widget
-And then we can add the widget to the Account page at `src/Account.js`:
+And then we can add the widget to the Account page at `src/Account.jsx`:
-```jsx title=src/Account.js
+```jsx title=src/Account.jsx
// Import the new component
import Avatar from './Avatar'
@@ -386,9 +377,9 @@ return (
<Avatar
url={avatar_url}
size={150}
- onUpload={(url) => {
+ onUpload={(event, url) => {
setAvatarUrl(url)
- updateProfile({ username, website, avatar_url: url })
+ updateProfile(event)
}}
/>
{/* ... */}