The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Look, it is pretty now 😊
Rodrigo Mansueli Nunesf4c3497dce39
diff --git a/apps/www/_blog/2023-08-01-react-native-file-upload.mdx b/apps/www/_blog/2023-08-01-react-native-file-upload.mdxindex d243ecf1370..361c57be6ab 100644--- a/apps/www/_blog/2023-08-01-react-native-file-upload.mdx+++ b/apps/www/_blog/2023-08-01-react-native-file-upload.mdx@@ -42,7 +42,7 @@ After a minute your project should be ready, and we can configure the authenticaAuthentication will be enabled by default, but we want to turn off email confirmation for this tutorial.-Select **Authentication** from the menu, go to the **Providers** section, and expand Email.+Select **Authentication** from the menu, go to the **Providers** section, and expand Email.@@ -114,26 +114,26 @@ EXPO_PUBLIC_SUPABASE_ANON_KEY=We can now simply read those values from the environment variables and initialize the Supabase client, so create a file at `config/initSupabase.ts` and add the following code:```ts-import * as SecureStore from 'expo-secure-store';-import 'react-native-url-polyfill/auto';+import * as SecureStore from 'expo-secure-store'+import 'react-native-url-polyfill/auto'-import { createClient } from '@supabase/supabase-js';+import { createClient } from '@supabase/supabase-js'// Use a custom secure storage solution for the Supabase client to store the JWTconst ExpoSecureStoreAdapter = {getItem: (key: string) => {- return SecureStore.getItemAsync(key);+ return SecureStore.getItemAsync(key)},setItem: (key: string, value: string) => {- SecureStore.setItemAsync(key, value);+ SecureStore.setItemAsync(key, value)},removeItem: (key: string) => {- SecureStore.deleteItemAsync(key);+ SecureStore.deleteItemAsync(key)},-};+}-const url = process.env.EXPO_PUBLIC_SUPABASE_URL;-const key = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY;+const url = process.env.EXPO_PUBLIC_SUPABASE_URL+const key = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY// Initialize the Supabase clientexport const supabase = createClient(url, key, {@@ -141,7 +141,7 @@ export const supabase = createClient(url, key, {storage: ExpoSecureStoreAdapter as any,detectSessionInUrl: false,},-});+})```We are using the SecureStore from Expo to handle the session of our Supabase client and add in the `createClient` function.@@ -155,41 +155,41 @@ Currently, the app won't work as we have no entry point. Because we are using thOn this page we will handle both login and registration, so let's start by creating a simple form with a few inputs and buttons inside the `app/index.tsx` file:```tsx-import { Alert, View, Button, TextInput, StyleSheet, Text, TouchableOpacity } from 'react-native';-import { useState } from 'react';-import React from 'react';-import Spinner from 'react-native-loading-spinner-overlay';-import { supabase } from '../config/initSupabase';+import { Alert, View, Button, TextInput, StyleSheet, Text, TouchableOpacity } from 'react-native'+import { useState } from 'react'+import React from 'react'+import Spinner from 'react-native-loading-spinner-overlay'+import { supabase } from '../config/initSupabase'const Login = () => {- const [email, setEmail] = useState('');- const [password, setPassword] = useState('');- const [loading, setLoading] = useState(false);+ const [email, setEmail] = useState('')+ const [password, setPassword] = useState('')+ const [loading, setLoading] = useState(false)// Sign in with email and passwordconst onSignInPress = async () => {- setLoading(true);+ setLoading(true)const { error } = await supabase.auth.signInWithPassword({email,password,- });+ })- if (error) Alert.alert(error.message);- setLoading(false);- };+ if (error) Alert.alert(error.message)+ setLoading(false)+ }// Create a new userconst onSignUpPress = async () => {- setLoading(true);+ setLoading(true)const { error } = await supabase.auth.signUp({email: email,password: password,- });+ })- if (error) Alert.alert(error.message);- setLoading(false);- };+ if (error) Alert.alert(error.message)+ setLoading(false)+ }return (<View style={styles.container}>@@ -197,16 +197,28 @@ const Login = () => {<Text style={styles.header}>My Cloud</Text>- <TextInput autoCapitalize="none" placeholder="[email protected]" value={email} onChangeText={setEmail} style={styles.inputField} />- <TextInput placeholder="password" value={password} onChangeText={setPassword} secureTextEntry style={styles.inputField} />+ <TextInput+ autoCapitalize="none"+ placeholder="[email protected]"+ value={email}+ onChangeText={setEmail}+ style={styles.inputField}+ />+ <TextInput+ placeholder="password"+ value={password}+ onChangeText={setPassword}+ secureTextEntry+ style={styles.inputField}+ /><TouchableOpacity onPress={onSignInPress} style={styles.button}><Text style={{ color: '#fff' }}>Sign in</Text></TouchableOpacity><Button onPress={onSignUpPress} title="Create Account" color={'#fff'}></Button></View>- );-};+ )+}const styles = StyleSheet.create({container: {@@ -238,9 +250,9 @@ const styles = StyleSheet.create({padding: 12,borderRadius: 4,},-});+})-export default Login;+export default Login```There's nothing fancy going on here, but this is all we need to use Supabase Authentication in our app!@@ -256,55 +268,55 @@ We will wrap a Provider around our app, which will use the `onAuthStateChange` fFor this, create a new file at `provider/AuthProvider.tsx` and add the following code:```tsx-import React, { useState, useEffect, createContext, PropsWithChildren } from 'react';-import { Session, User } from '@supabase/supabase-js';-import { supabase } from '../config/initSupabase';+import React, { useState, useEffect, createContext, PropsWithChildren } from 'react'+import { Session, User } from '@supabase/supabase-js'+import { supabase } from '../config/initSupabase'type AuthProps = {- user: User | null;- session: Session | null;- initialized?: boolean;- signOut?: () => void;-};+ user: User | null+ session: Session | null+ initialized?: boolean+ signOut?: () => void+}-export const AuthContext = createContext<Partial<AuthProps>>({});+export const AuthContext = createContext<Partial<AuthProps>>({})// Custom hook to read the context valuesexport function useAuth() {- return React.useContext(AuthContext);+ return React.useContext(AuthContext)}export const AuthProvider = ({ children }: PropsWithChildren) => {- const [user, setUser] = useState<User | null>();- const [session, setSession] = useState<Session | null>(null);- const [initialized, setInitialized] = useState<boolean>(false);+ const [user, setUser] = useState<User | null>()+ const [session, setSession] = useState<Session | null>(null)+ const [initialized, setInitialized] = useState<boolean>(false)useEffect(() => {// Listen for changes to authentication stateconst { data } = supabase.auth.onAuthStateChange(async (event, session) => {- setSession(session);- setUser(session ? session.user : null);- setInitialized(true);- });+ setSession(session)+ setUser(session ? session.user : null)+ setInitialized(true)+ })return () => {- data.subscription.unsubscribe();- };- }, []);+ data.subscription.unsubscribe()+ }+ }, [])// Log out the userconst signOut = async () => {- await supabase.auth.signOut();- };+ await supabase.auth.signOut()+ }const value = {user,session,initialized,signOut,- };+ }- return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;-};+ return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>+}```To use the context we can now wrap it around our app, and while we do this we can also take care of the navigation:@@ -314,33 +326,33 @@ In the topmost layout file we can check whether a user has an active session orTo make this work with the Expo Router we can create a file at `app/_layout.tsx` and add the following code:```tsx-import { Slot, useRouter, useSegments } from 'expo-router';-import { useEffect } from 'react';-import { AuthProvider, useAuth } from '../provider/AuthProvider';+import { Slot, useRouter, useSegments } from 'expo-router'+import { useEffect } from 'react'+import { AuthProvider, useAuth } from '../provider/AuthProvider'// Makes sure the user is authenticated before accessing protected pagesconst InitialLayout = () => {- const { session, initialized } = useAuth();- const segments = useSegments();- const router = useRouter();+ const { session, initialized } = useAuth()+ const segments = useSegments()+ const router = useRouter()useEffect(() => {- if (!initialized) return;+ if (!initialized) return// Check if the path/url is in the (auth) group- const inAuthGroup = segments[0] === '(auth)';+ const inAuthGroup = segments[0] === '(auth)'if (session && !inAuthGroup) {// Redirect authenticated users to the list page- router.replace('/list');+ router.replace('/list')} else if (!session) {// Redirect unauthenticated users to the login page- router.replace('/');+ router.replace('/')}- }, [session, initialized]);+ }, [session, initialized])- return <Slot />;-};+ return <Slot />+}// Wrap the app with the AuthProviderconst RootLayout = () => {@@ -348,10 +360,10 @@ const RootLayout = () => {<AuthProvider><InitialLayout /></AuthProvider>- );-};+ )+}-export default RootLayout;+export default RootLayout```Whenever the `initialized` or `session` state changes, we check if the user is authenticated and redirect her to the correct page.@@ -367,15 +379,15 @@ Now that we have the authentication set up, we can start working on the file uplFirst, let's define another layout for this inside area so create a file at `/app/(auth)/_layout.tsx` and add the following code:```tsx-import { Stack } from 'expo-router';-import { useAuth } from '../../provider/AuthProvider';-import React from 'react';-import { TouchableOpacity } from 'react-native';-import { Ionicons } from '@expo/vector-icons';+import { Stack } from 'expo-router'+import { useAuth } from '../../provider/AuthProvider'+import React from 'react'+import { TouchableOpacity } from 'react-native'+import { Ionicons } from '@expo/vector-icons'// Simple stack layout within the authenticated areaconst StackLayout = () => {- const { signOut } = useAuth();+ const { signOut } = useAuth()return (<Stack@@ -384,7 +396,8 @@ const StackLayout = () => {backgroundColor: '#0f0f0f',},headerTintColor: '#fff',- }}>+ }}+ ><Stack.Screenname="list"options={{@@ -394,12 +407,13 @@ const StackLayout = () => {<Ionicons name="log-out-outline" size={30} color={'#fff'} /></TouchableOpacity>),- }}></Stack.Screen>+ }}+ ></Stack.Screen></Stack>- );-};+ )+}-export default StackLayout;+export default StackLayout```This defines a simple stack navigation and adds a button to trigger the logout, so we can now also fully test the authentication flow.@@ -411,37 +425,37 @@ You won't have any files to show yet, but loading the files of a user is as easyAdditionally, we add a little FAB (floating action button) to trigger the file picker, so create a file at `/app/(auth)/list.tsx` and add the following code:```tsx-import { View, StyleSheet, TouchableOpacity, ScrollView } from 'react-native';-import React, { useEffect, useState } from 'react';-import { Ionicons } from '@expo/vector-icons';-import * as ImagePicker from 'expo-image-picker';-import { useAuth } from '../../provider/AuthProvider';-import * as FileSystem from 'expo-file-system';-import { decode } from 'base64-arraybuffer';-import { supabase } from '../../config/initSupabase';-import { FileObject } from '@supabase/storage-js';+import { View, StyleSheet, TouchableOpacity, ScrollView } from 'react-native'+import React, { useEffect, useState } from 'react'+import { Ionicons } from '@expo/vector-icons'+import * as ImagePicker from 'expo-image-picker'+import { useAuth } from '../../provider/AuthProvider'+import * as FileSystem from 'expo-file-system'+import { decode } from 'base64-arraybuffer'+import { supabase } from '../../config/initSupabase'+import { FileObject } from '@supabase/storage-js'const list = () => {- const { user } = useAuth();- const [files, setFiles] = useState<FileObject[]>([]);+ const { user } = useAuth()+ const [files, setFiles] = useState<FileObject[]>([])useEffect(() => {- if (!user) return;+ if (!user) return// Load user images- loadImages();- }, [user]);+ loadImages()+ }, [user])const loadImages = async () => {- const { data } = await supabase.storage.from('files').list(user!.id);+ const { data } = await supabase.storage.from('files').list(user!.id)if (data) {- setFiles(data);+ setFiles(data)}- };+ }const onSelectImage = async () => {// TODO- };+ }return (<View style={styles.container}>@@ -450,8 +464,8 @@ const list = () => {<Ionicons name="camera-outline" size={30} color={'#fff'} /></TouchableOpacity></View>- );-};+ )+}const styles = StyleSheet.create({container: {@@ -471,9 +485,9 @@ const styles = StyleSheet.create({backgroundColor: '#2b825b',borderRadius: 100,},-});+})-export default list;+export default list```This should give us a nice and clean UI.@@ -493,40 +507,52 @@ To finally display them we will add a `ScrollView` component, which will renderLet's start by creating those component rows in another file, so create a `components/ImageItem.tsx` file and add the following code:```tsx-import { FileObject } from '@supabase/storage-js';-import { Image, View, Text, TouchableOpacity } from 'react-native';-import { supabase } from '../config/initSupabase';-import { useState } from 'react';-import { Ionicons } from '@expo/vector-icons';+import { FileObject } from '@supabase/storage-js'+import { Image, View, Text, TouchableOpacity } from 'react-native'+import { supabase } from '../config/initSupabase'+import { useState } from 'react'+import { Ionicons } from '@expo/vector-icons'// Image item component that displays the image from Supabase Storage and a delte button-const ImageItem = ({ item, userId, onRemoveImage }: { item: FileObject; userId: string; onRemoveImage: () => void }) => {- const [image, setImage] = useState<string>('');+const ImageItem = ({+ item,+ userId,+ onRemoveImage,+}: {+ item: FileObject+ userId: string+ onRemoveImage: () => void+}) => {+ const [image, setImage] = useState<string>('')supabase.storage.from('files').download(`${userId}/${item.name}`).then(({ data }) => {- const fr = new FileReader();- fr.readAsDataURL(data!);+ const fr = new FileReader()+ fr.readAsDataURL(data!)fr.onload = () => {- setImage(fr.result as string);- };- });+ setImage(fr.result as string)+ }+ })return (<View style={{ flexDirection: 'row', margin: 1, alignItems: 'center', gap: 5 }}>- {image ? <Image style={{ width: 80, height: 80 }} source={{ uri: image }} /> : <View style={{ width: 80, height: 80, backgroundColor: '#1A1A1A' }} />}+ {image ? (+ <Image style={{ width: 80, height: 80 }} source={{ uri: image }} />+ ) : (+ <View style={{ width: 80, height: 80, backgroundColor: '#1A1A1A' }} />+ )}<Text style={{ flex: 1, color: '#fff' }}>{item.name}</Text>{/* Delete image button */}<TouchableOpacity onPress={onRemoveImage}><Ionicons name="trash-outline" size={20} color={'#fff'} /></TouchableOpacity></View>- );-};+ )+}-export default ImageItem;+export default ImageItem```This component will display the image from Supabase Storage, the name of the file and a delete button.@@ -536,20 +562,25 @@ To display the image we use the `download()` method from the storage client, whiNow let's use this component in our `list.tsx` file to render the list of images by updating the `return` statement:```tsx- return (- <View style={styles.container}>- <ScrollView>- {files.map((item, index) => (- <ImageItem key={item.id} item={item} userId={user!.id} onRemoveImage={() => onRemoveImage(item, index)} />- ))}- </ScrollView>-- {/* FAB to add images */}- <TouchableOpacity onPress={onSelectImage} style={styles.fab}>- <Ionicons name="camera-outline" size={30} color={'#fff'} />- </TouchableOpacity>- </View>- );+return (+ <View style={styles.container}>+ <ScrollView>+ {files.map((item, index) => (+ <ImageItem+ key={item.id}+ item={item}+ userId={user!.id}+ onRemoveImage={() => onRemoveImage(item, index)}+ />+ ))}+ </ScrollView>++ {/* FAB to add images */}+ <TouchableOpacity onPress={onSelectImage} style={styles.fab}>+ <Ionicons name="camera-outline" size={30} color={'#fff'} />+ </TouchableOpacity>+ </View>+)```Don't forget to also include the import to the `ImageItem` component!@@ -559,12 +590,12 @@ Don't forget to also include the import to the `ImageItem` component!Finally, we can also include the delete functionality by adding the following code to the `list.tsx`:```tsx- const onRemoveImage = async (item: FileObject, listIndex: number) => {- supabase.storage.from('files').remove([`${user!.id}/${item.name}`]);- const newFiles = [...files];- newFiles.splice(listIndex, 1);- setFiles(newFiles);- };+const onRemoveImage = async (item: FileObject, listIndex: number) => {+ supabase.storage.from('files').remove([`${user!.id}/${item.name}`])+ const newFiles = [...files]+ newFiles.splice(listIndex, 1)+ setFiles(newFiles)+}```We are handling the deletion here so we can accordingly update the state of the files list after removing an item.