Issue #942

Expose supabase with createClient

useSupabase.ts

import { createClient } from '@supabase/supabase-js'

const supabaseUrl = process.env.SUPABASE_URL
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY

export const supabase = createClient(supabaseUrl!, supabaseAnonKey!)

export const signIn = async () => {
    await supabase.auth.signInWithOAuth({
        provider: 'twitter'
    });
}

export const signOut = async () => {
    await supabase.auth.signOut();
}

Wrap auth state in React Context

AuthProvider.tsx

import React, { useContext, createContext, useState, useEffect } from 'react'
import { Session, User } from '@supabase/supabase-js'
import { supabase } from './useSupabase'

interface AuthProviderProps {
    children: React.ReactNode
}

type AuthContextType = {
    session: Session | null,
    user: User | null
}

const AuthContext = createContext<AuthContextType>({
    session: null,
    user: null
})

const AuthProvider = (props: AuthProviderProps) => {
    const [user, setUser] = useState<User | null>(null)
    const [session, setSession] = useState<Session | null>(null)
    const [loading, setLoading] = useState<boolean>(true)

    useEffect(() => {
        const { data: listener } = supabase.auth.onAuthStateChange((_event, session) => {
            setSession(session)
            setUser(session?.user || null)
            setLoading(false)
        })

        const setData = async () => {
            const { data : {session}, error } = await supabase.auth.getSession()
            if (error) {
                throw error
            }

            setSession(session)
            setUser(session?.user || null)
            setLoading(false)
        }

        setData()
        
        return () => {
            listener?.subscription.unsubscribe()    
        }
    }, [])

    const value = {
        session,
        user
    }

    return (
        <AuthContext.Provider value={value}>
            {props.children}
        </AuthContext.Provider>
    )
}

export const useAuth = () => {
    return useContext(AuthContext)
}

export default AuthProvider