Skip to content

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

Creating full example with scrolling, fake auth, and store

Paul Copplestoneff5d58d73d25
diff --git a/examples/slack-clone/components/Layout.js b/examples/slack-clone/components/Layout.js
index 94479ddb4e3..3423c3f80e0 100644
--- a/examples/slack-clone/components/Layout.js
+++ b/examples/slack-clone/components/Layout.js
@@ -1,26 +1,69 @@
import '~/styles/style.scss'
import Link from 'next/link'
+import { useContext, useEffect } from 'react'
+import UserContext from '~/lib/UserContext'
+import { addChannel } from '~/lib/Store'
-export default props => (
- <main className="main">
- <div className="flex mb-4">
- {/* Sidebar */}
- <nav className="w-1/4 bg-gray-900 text-gray-100">
- <div className="p-2">
- <h4 className="font-bold">Channels</h4>
- <ul className="channel-list">
- {props.channels.map(x => (
- <SidebarItem channel={x} key={x.id} />
- ))}
- </ul>
- </div>
- </nav>
+export default props => {
+ const { signOut } = useContext(UserContext)
- {/* Messages */}
- <div className="w-3/4 bg-gray-800">{props.children}</div>
- </div>
- </main>
-)
+ const slugify = text => {
+ return text
+ .toString()
+ .toLowerCase()
+ .replace(/\s+/g, '-') // Replace spaces with -
+ .replace(/[^\w\-]+/g, '') // Remove all non-word chars
+ .replace(/\-\-+/g, '-') // Replace multiple - with single -
+ .replace(/^-+/, '') // Trim - from start of text
+ .replace(/-+$/, '') // Trim - from end of text
+ }
+
+ const newChannel = async () => {
+ const slug = prompt('Please enter your name')
+ if (slug) {
+ // let { body } = await
+ addChannel(slugify(slug))
+ // console.log('body', body)
+ }
+ }
+
+ return (
+ <main className="main flex mb-4 h-screen w-screen absolute">
+ {/* Sidebar */}
+ <nav className="w-1/4 bg-gray-900 text-gray-100 h-screen">
+ <div className="p-2">
+ <h4 className="font-bold">Channels</h4>
+ <ul className="channel-list">
+ {props.channels.map(x => (
+ <SidebarItem channel={x} key={x.id} />
+ ))}
+ </ul>
+ </div>
+ <hr className="m-2" />
+ <div className="p-2">
+ <button
+ className="bg-blue-900 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded w-full"
+ onClick={() => newChannel()}
+ >
+ New Channel
+ </button>
+ </div>
+ <hr className="m-2" />
+ <div className="p-2">
+ <button
+ className="bg-blue-900 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded w-full"
+ onClick={() => signOut()}
+ >
+ Log out
+ </button>
+ </div>
+ </nav>
+
+ {/* Messages */}
+ <div className="w-3/4 bg-gray-800 h-screen">{props.children}</div>
+ </main>
+ )
+}
const SidebarItem = ({ channel }) => (
<>
diff --git a/examples/slack-clone/components/Message.js b/examples/slack-clone/components/Message.js
index 548eddf0a14..1590a0ab9c0 100644
--- a/examples/slack-clone/components/Message.js
+++ b/examples/slack-clone/components/Message.js
@@ -1,10 +1,8 @@
const Message = ({ message }) => (
<>
- <div className="flex items-center">
- <div className="">
- <p className="text-white font-bold">{message.user_id}</p>
- <p className="text-white">{message.message}</p>
- </div>
+ <div className="py-1">
+ <p className="text-blue-700 font-bold">{message.author.username}</p>
+ <p className="text-white">{message.message}</p>
</div>
</>
)
diff --git a/examples/slack-clone/components/MessageInput.js b/examples/slack-clone/components/MessageInput.js
index b696948adb8..cbc81b71185 100644
--- a/examples/slack-clone/components/MessageInput.js
+++ b/examples/slack-clone/components/MessageInput.js
@@ -13,7 +13,6 @@ const MessageInput = ({onSubmit}) => {
return (
<>
- <div className="mb-4">
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
type="text"
@@ -22,7 +21,6 @@ const MessageInput = ({onSubmit}) => {
onChange={e => setMessageText(e.target.value)}
onKeyDown={e => submitOnEnter(e)}
/>
- </div>
</>
)}
diff --git a/examples/slack-clone/db/00-schema.sql b/examples/slack-clone/db/00-schema.sql
index 399027cba6c..133f64fe970 100644
--- a/examples/slack-clone/db/00-schema.sql
+++ b/examples/slack-clone/db/00-schema.sql
@@ -21,7 +21,7 @@ CREATE TABLE public.channels (
inserted_at timestamp without time zone DEFAULT timezone('utc'::text, now()) NOT NULL,
updated_at timestamp without time zone DEFAULT timezone('utc'::text, now()) NOT NULL,
data jsonb DEFAULT null,
- slug text
+ slug text NOT NULL UNIQUE
);
ALTER TABLE public.users REPLICA IDENTITY FULL; -- Send "previous data" to supabase
COMMENT ON COLUMN public.channels.data IS 'For unstructured data and prototyping.';
diff --git a/examples/slack-clone/lib/Store.js b/examples/slack-clone/lib/Store.js
new file mode 100644
index 00000000000..88f42bb2217
--- /dev/null
+++ b/examples/slack-clone/lib/Store.js
@@ -0,0 +1,160 @@
+import { useState, useEffect } from 'react'
+import { createClient } from '@supabase/supabase-js'
+
+const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)
+
+/**
+ * @param {number} channelId the currently selected Channel
+ */
+export const useStore = props => {
+ const [channels, setChannels] = useState(new Array())
+ const [messages, setMessages] = useState(new Array())
+ const [users] = useState(new Map())
+ const [newMessage, handleNewMessage] = useState(null)
+ const [newChannel, handleNewChannel] = useState(null)
+ const [newOrUpdatedUser, handleNewOrUpdatedUser] = useState(null)
+
+ // Load initial data and set up listeners
+ useEffect(() => {
+ // Get Channels
+ fetchChannels(setChannels)
+ // Listen for new messages
+ const messageListener = supabase
+ .from('messages')
+ .on('*', payload => handleNewMessage(payload.new))
+ .subscribe()
+ // Listen for changes to our users
+ const userListener = supabase
+ .from('users')
+ .on('*', payload => handleNewOrUpdatedUser(payload.new))
+ .subscribe()
+ // Listen for new channels
+ const channelListener = supabase
+ .from('channels')
+ .on('*', payload => handleNewChannel(payload.new))
+ .subscribe()
+ // Cleanup on unmount
+ // return () => {
+ // messageListener.unsubscribe()
+ // userListener.unsubscribe()
+ // channelListener.unsubscribe()
+ // }
+ }, [])
+
+ // Update when the route changes
+ useEffect(() => {
+ fetchMessages(props.channelId, messages => {
+ messages.forEach(x => users.set(x.user_id, x.author))
+ setMessages(messages)
+ })
+ }, [props.channelId])
+
+ // New message recieved from Postgres
+ useEffect(() => {
+ if (newMessage) {
+ const handleAsync = async () => {
+ let authorId = newMessage.user_id
+ if (!users.get(authorId)) await fetchUser(authorId, user => handleNewOrUpdatedUser(user))
+ setMessages(messages.concat(newMessage))
+ }
+ handleAsync()
+ }
+ }, [newMessage])
+
+ // New channel recieved from Postgres
+ useEffect(() => {
+ if (newChannel) setChannels(channels.concat(newChannel))
+ }, [newChannel])
+
+ // New or updated user recieved from Postgres
+ useEffect(() => {
+ if (newOrUpdatedUser) users.set(newOrUpdatedUser.id, newOrUpdatedUser)
+ }, [newOrUpdatedUser])
+
+ return {
+ // We can export computed values here to map the authors to each message
+ messages: messages.map(x => ({ ...x, author: users.get(x.user_id) })),
+ channels: channels.sort((a, b) => a.slug.localeCompare(b.slug)),
+ users,
+ }
+}
+
+/**
+ * Fetch all channels
+ * @param {function} setState Optionally pass in a hook or callback to set the state
+ */
+export const fetchChannels = async setState => {
+ try {
+ let { body } = await supabase.from('channels').select('*')
+ if (setState) setState(body)
+ return body
+ } catch (error) {
+ console.log('error', error)
+ }
+}
+
+/**
+ * Fetch a single user
+ * @param {number} userId
+ * @param {function} setState Optionally pass in a hook or callback to set the state
+ */
+export const fetchUser = async (userId, setState) => {
+ try {
+ let { body } = await supabase
+ .from('users')
+ .eq('id', userId)
+ .select(`*`)
+ let user = body[0]
+ if (setState) setState(user)
+ return user
+ } catch (error) {
+ console.log('error', error)
+ }
+}
+
+/**
+ * Fetch all messages and their authors
+ * @param {number} channelId
+ * @param {function} setState Optionally pass in a hook or callback to set the state
+ */
+export const fetchMessages = async (channelId, setState) => {
+ try {
+ let { body } = await supabase
+ .from('messages')
+ .eq('channel_id', channelId)
+ .select(`*, author:user_id(*)`)
+ .order('inserted_at', true)
+ if (setState) setState(body)
+ return body
+ } catch (error) {
+ console.log('error', error)
+ }
+}
+
+/**
+ * Insert a new channel into the DB
+ * @param {string} slug The channel name
+ */
+export const addChannel = async slug => {
+ try {
+ let { body } = await supabase.from('channels').insert([{ slug }])
+ return body
+ } catch (error) {
+ console.log('error', error)
+ }
+}
+
+/**
+ * Insert a new message into the DB
+ * @param {string} message The message text
+ * @param {number} channel_id
+ * @param {number} user_id The author
+ */
+export const addMessage = async (message, channel_id, user_id) => {
+ try {
+ let { body } = await supabase.from('messages').insert([{ message, channel_id, user_id }])
+ return body
+ } catch (error) {
+ console.log('error', error)
+ }
+}
diff --git a/examples/slack-clone/lib/UserContext.js b/examples/slack-clone/lib/UserContext.js
new file mode 100644
index 00000000000..ee09678f508
--- /dev/null
+++ b/examples/slack-clone/lib/UserContext.js
@@ -0,0 +1,5 @@
+import { createContext } from 'react'
+
+const UserContext = createContext()
+
+export default UserContext
diff --git a/examples/slack-clone/pages/_app.js b/examples/slack-clone/pages/_app.js
new file mode 100644
index 00000000000..b05d12cc181
--- /dev/null
+++ b/examples/slack-clone/pages/_app.js
@@ -0,0 +1,69 @@
+import React from 'react'
+import App from 'next/app'
+import Router from 'next/router'
+import UserContext from '~/lib/UserContext'
+import { createClient } from '@supabase/supabase-js'
+
+const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)
+
+export default class SupabaseSlackClone extends App {
+ state = {
+ authLoaded: false,
+ user: null,
+ }
+
+ componentDidMount = () => {
+ const user = localStorage.getItem('supabase-slack-clone')
+ if (user) this.setState({ user, authLoaded: true })
+ else Router.push('/')
+ }
+
+ /**
+ * Dummy function
+ * DO NOT USE IN PRODUCTION
+ */
+ signIn = async username => {
+ var user = {}
+ let { body } = await supabase
+ .from('users')
+ .match({ username })
+ .select('id, username')
+ if (!body.length) {
+ // @TODO: upsert
+ await supabase.from('users').insert([{ username }])
+ let { body } = await supabase
+ .from('users')
+ .match({ username })
+ .select('id, username')
+ user = body[0].id
+ } else {
+ user = body[0].id
+ }
+ localStorage.setItem('supabase-slack-clone', user)
+ this.setState({ user }, () => {
+ Router.push('/channels/[id]', '/channels/1')
+ })
+ }
+
+ signOut = () => {
+ localStorage.removeItem('supabase-slack-clone')
+ this.setState({ user: null })
+ Router.push('/')
+ }
+
+ render() {
+ const { Component, pageProps } = this.props
+ return (
+ <UserContext.Provider
+ value={{
+ authLoaded: this.state.authLoaded,
+ user: this.state.user,
+ signIn: this.signIn,
+ signOut: this.signOut,
+ }}
+ >
+ <Component {...pageProps} />
+ </UserContext.Provider>
+ )
+ }
+}
diff --git a/examples/slack-clone/pages/channels/[id].js b/examples/slack-clone/pages/channels/[id].js
index 6b6fa75a71e..ecab800cb6d 100644
--- a/examples/slack-clone/pages/channels/[id].js
+++ b/examples/slack-clone/pages/channels/[id].js
@@ -1,117 +1,48 @@
-/**
- * Fat controller!
- * Think of this page as a store that controls all the data flow.
- */
import Layout from '~/components/Layout'
import Message from '~/components/Message'
import MessageInput from '~/components/MessageInput'
-import { useState, useEffect } from 'react'
-import { createClient } from '@supabase/supabase-js'
import { useRouter } from 'next/router'
-
-const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)
+import { useStore, addMessage } from '~/lib/Store'
+import { useContext, useEffect, useRef } from 'react'
+import UserContext from '~/lib/UserContext'
const ChannelsPage = props => {
const router = useRouter()
- const { id: channelId } = router.query
- const [channels, setChannels] = useState([])
- const [messages, setMessages] = useState([])
- const [change, notifyDbChange] = useState(null)
+ const { user, authLoaded, signOut } = useContext(UserContext)
+ const messagesEndRef = useRef(null)
- // Initial load of data
+ // Redirect if not signed in.
useEffect(() => {
- setChannels(props.channels)
- supabase
- .from('messages')
- .on('*', payload => {
- notifyDbChange(payload.new)
- })
- .subscribe()
- }, [])
+ if (authLoaded && !user) signOut()
+ }, [user, router])
- // On change update messages
- useEffect(() => {
- if (change) setMessages(messages.concat(change))
- }, [change])
+ // Else load up the page
+ const { id: channelId } = router.query
+ const { messages, channels } = useStore({ channelId })
- // Update when the route changes
useEffect(() => {
- try {
- getMessages(channelId, setMessages)
- } catch (error) {
- console.log('Error: ', error)
- }
- }, [router.query.id])
+ console.log('messagesEndRef', messagesEndRef)
+ messagesEndRef.current.scrollIntoView({ block: 'start', behavior: 'smooth' })
+ }, [messages])
// Render the channels and messages
return (
<Layout channels={channels}>
- <div className="p-2">
- {messages.map(x => (
- <Message key={x.id} message={x} />
- ))}
- </div>
- <div className="p-2">
- <MessageInput onSubmit={text => addMessage(text, channelId, 2)} />
+ <div className="relative h-screen">
+ <div className="Messages h-full pb-16">
+ <div className="p-2 overflow-y-auto">
+ {messages.map(x => (
+ <Message key={x.id} message={x} />
+ ))}
+ <div ref={messagesEndRef} style={{height: 0}} />
+ </div>
+ </div>
+ <div className="p-2 absolute bottom-0 left-0 w-full">
+ <MessageInput onSubmit={async text => addMessage(text, channelId, user)} />
+ </div>
</div>
</Layout>
)
}
-/**
- * Hydrate the page on initial load
- */
-ChannelsPage.getInitialProps = async () => {
- let channels = await getChannels()
- return { channels }
-}
-
-/**
- * Get all channels
- * @param {function} setState Optionally pass in a hook or callback to set the state
- */
-const getChannels = async setState => {
- try {
- let { body } = await supabase.from('channels').select('*')
- if (setState) setState(body)
- return body
- } catch (error) {
- console.log('error', error)
- }
-}
-
-/**
- * Get all messages and their authors
- * @param {number} channelId
- * @param {function} setState Optionally pass in a hook or callback to set the state
- */
-const getMessages = async (channelId, setState) => {
- try {
- let { body } = await supabase
- .from('messages')
- .eq('channel_id', channelId)
- .select(`*, author:user_id(*)`)
- .order('inserted_at', true)
- if (setState) setState(body)
- return body
- } catch (error) {
- console.log('error', error)
- }
-}
-
-/**
- * Insert a new message
- * @param {string} message The message text
- * @param {number} channel_id
- * @param {number} user_id The author
- */
-const addMessage = async (message, channel_id, user_id) => {
- try {
- let { body } = await supabase.from('messages').insert([{ message, channel_id, user_id }])
- return body
- } catch (error) {
- console.log('error', error)
- }
-}
-
export default ChannelsPage
diff --git a/examples/slack-clone/pages/index.js b/examples/slack-clone/pages/index.js
index 3de14e30da6..f228328ef53 100644
--- a/examples/slack-clone/pages/index.js
+++ b/examples/slack-clone/pages/index.js
@@ -1,16 +1,20 @@
import '~/styles/style.scss'
import { useRouter } from 'next/router'
+import { useState, useContext } from 'react'
+import UserContext from '../lib/UserContext'
const Home = props => {
const router = useRouter()
+ const { signIn } = useContext(UserContext)
+ const [username, setUsername] = useState('')
const handleLogin = e => {
e.preventDefault()
- router.push('/channels/[id]', '/channels/1')
+ if (username != '') signIn(username)
}
return (
- <div className="container mx-auto h-full flex justify-center items-center mt-8">
+ <div className="container mx-auto h-full flex justify-center items-center">
<div className="w-1/3 mt-8">
<div className="border-teal p-8 border-t-12 bg-white mb-6 rounded-lg shadow-lg">
<div className="mb-4">
@@ -19,6 +23,7 @@ const Home = props => {
type="text"
className="block appearance-none w-full bg-white border border-grey-light hover:border-grey px-2 py-2 rounded shadow"
placeholder="Your Username"
+ onChange={e => setUsername(e.target.value)}
/>
</div>
diff --git a/examples/slack-clone/styles/style.scss b/examples/slack-clone/styles/style.scss
index 03df273af4b..0ba46b3847f 100644
--- a/examples/slack-clone/styles/style.scss
+++ b/examples/slack-clone/styles/style.scss
@@ -2,6 +2,13 @@
@import "~tailwindcss/dist/components.css";
@import "~tailwindcss/dist/utilities.css";
+html, body, #__next, .main {
+ max-height: 100vh;
+ height: 100vh;
+ margin: 0;
+ padding: 0;
+ overflow: hidden;
+}
.channel-list {
li a:before {
content: '# ';
@@ -10,4 +17,9 @@
li a:hover {
opacity: 0.9;
}
+}
+.Messages {
+ overflow:auto;
+ display: flex;
+ flex-direction: column-reverse;
}
\ No newline at end of file