init commit,

This commit is contained in:
louiscklaw
2025-05-28 09:55:51 +08:00
commit efe70ceb69
8042 changed files with 951668 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
import supabase from '../../utils/supabase'
import RealtimePosts from './realtime-posts'
// do not cache this page
export const revalidate = 0
// this component fetches the current posts server-side
// and subscribes to new posts client-side
export default async function Realtime() {
const { data } = await supabase.from('posts').select('*')
// data can be passed from server components to client components
// this allows us to fetch the initial posts before rendering the page
// our <RealtimePosts /> component will then subscribe to new posts client-side
return <RealtimePosts serverPosts={data} />
}

View File

@@ -0,0 +1,34 @@
'use client'
import { useEffect, useState } from 'react'
import supabase from '../../utils/supabase'
// realtime subscriptions need to be set up client-side
// this component takes initial posts as props and automatically
// updates when new posts are inserted into Supabase's `posts` table
export default function RealtimePosts({ serverPosts }: { serverPosts: any }) {
const [posts, setPosts] = useState(serverPosts)
useEffect(() => {
// this overwrites `posts` any time the `serverPosts` prop changes
// this happens when the parent Server Component is re-rendered
setPosts(serverPosts)
}, [serverPosts])
useEffect(() => {
// ensure you have enabled replication on the `posts` table
// https://supabase.com/dashboard/project/_/database/replication
const channel = supabase
.channel('*')
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'posts' }, (payload) =>
setPosts((posts: any) => [...posts, payload.new])
)
.subscribe()
return () => {
supabase.removeChannel(channel)
}
}, [serverPosts])
return <pre>{JSON.stringify(posts, null, 2)}</pre>
}