Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SSR Support for React Hooks #2232

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion examples/nextjs/app/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import pgPkg from "pg"
const { Client } = pgPkg

const db = new Client({
connectionString: process.env.DATABASE_URL,
connectionString:
process.env.DATABASE_URL ||
`postgresql://postgres:password@localhost:54321/electric`,
})

db.connect()
Expand Down
100 changes: 100 additions & 0 deletions examples/nextjs/app/items-list.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"use client"

import { v4 as uuidv4 } from "uuid"
import { useOptimistic, startTransition } from "react"
import { useShape, getShapeStream } from "@electric-sql/react"
import { ItemsView } from "./items-view"
import { matchStream } from "./match-stream"
import { type Item } from "./types"
import { getClientShapeOptions } from "./items"

async function createItem(newId: string) {
const shapeOptions = getClientShapeOptions()
const itemsStream = getShapeStream<Item>(shapeOptions)

// Match the insert
const findUpdatePromise = matchStream({
stream: itemsStream,
operations: [`insert`],
matchFn: ({ message }) => message.value.id === newId,
})

// Generate new UUID and post to backend
const fetchPromise = fetch(`/api/items`, {
method: `POST`,
body: JSON.stringify({ uuid: newId }),
})

return await Promise.all([findUpdatePromise, fetchPromise])
}

async function clearItems() {
const shapeOptions = getClientShapeOptions()
const itemsStream = getShapeStream<Item>(shapeOptions)

// Match the delete
const findUpdatePromise = matchStream({
stream: itemsStream,
operations: [`delete`],
// First delete will match
matchFn: () => true,
})
// Post to backend to delete everything
const fetchPromise = fetch(`/api/items`, {
method: `DELETE`,
})

return await Promise.all([findUpdatePromise, fetchPromise])
}

export function ItemsList() {
const shapeOptions = getClientShapeOptions()
const { data: rows } = useShape<Item>(shapeOptions)
const [optimisticItems, updateOptimisticItems] = useOptimistic<
Item[],
{ newId?: string; isClear?: boolean }
>(rows, (state, { newId, isClear }) => {
// If clearing, return empty array
if (isClear) {
return []
}

// Create a new array combining all sources
const allItems = [...rows, ...state]
if (newId) {
const newItem = { id: newId, value: `Item ${newId.slice(0, 4)}` }
allItems.push(newItem)
}

// Deduplicate by id, keeping the last occurrence of each id
const uniqueItems = allItems.reduce((acc, item) => {
acc[item.id] = item
return acc
}, {} as Record<string, Item>)

return Object.values(uniqueItems)
})

const handleAdd = async () => {
const id = uuidv4()
startTransition(async () => {
updateOptimisticItems({ newId: id })
await createItem(id)
})
}

const handleClear = async () => {
startTransition(async () => {
updateOptimisticItems({ isClear: true })
await clearItems()
})
}

return (
<ItemsView
items={optimisticItems}
onAdd={handleAdd}
onClear={handleClear}
/>
)
}
34 changes: 34 additions & 0 deletions examples/nextjs/app/items-view.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { type Item } from "./types"

interface ItemsViewProps {
items: Item[]
onAdd?: () => void
onClear?: () => void
}

export function ItemsView({ items, onAdd, onClear }: ItemsViewProps) {
return (
<div className="container">
<div className="buttons">
{onAdd && (
<button onClick={onAdd} className="button">
Add
</button>
)}
{onClear && (
<button onClick={onClear} className="button">
Clear
</button>
)}
</div>
<br />
<div className="items">
{items.map((item) => (
<p key={item.id} className="item">
{item.id}
</p>
))}
</div>
</div>
)
}
25 changes: 25 additions & 0 deletions examples/nextjs/app/items.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { preloadShape } from "@electric-sql/react"
import { ShapeStreamOptions } from "@electric-sql/client"

// Server-side shape configuration
export const itemShapeOptions: ShapeStreamOptions = {
url: process.env.ELECTRIC_URL || `http://localhost:5173/shape-proxy`,
params: {
table: `items`,
},
}

// Client-side shape configuration
export const getClientShapeOptions = (): ShapeStreamOptions => {
return {
...itemShapeOptions,
url: `http://localhost:5173/shape-proxy`,
}
}

// Server component to prefetch shape data
export async function ItemsData() {
// Prefetch shape data during SSR
await preloadShape(itemShapeOptions)
return null
}
124 changes: 9 additions & 115 deletions examples/nextjs/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,120 +1,14 @@
"use client"

import { v4 as uuidv4 } from "uuid"
import { useOptimistic } from "react"
import { useShape, getShapeStream } from "@electric-sql/react"
import dynamic from 'next/dynamic'
import "./Example.css"
import { matchStream } from "./match-stream"
import { ShapeStreamOptions } from "@electric-sql/client/*"

const itemShape = (): ShapeStreamOptions => {
if (typeof window !== `undefined`) {
return {
url: new URL(`/shape-proxy`, window?.location.origin).href,
params: {
table: `items`,
},
}
} else {
return {
url: new URL(`https://not-sure-how-this-works.com/shape-proxy`).href,
params: {
table: `items`,
},
}
// Dynamic import of ItemsList with SSR disabled
const ClientItemsList = dynamic(
() => import('./items-list').then(mod => mod.ItemsList),
{
ssr: false,
}
}

type Item = { id: string }

async function createItem(newId: string) {
const itemsStream = getShapeStream<Item>(itemShape())

// Match the insert
const findUpdatePromise = matchStream({
stream: itemsStream,
operations: [`insert`],
matchFn: ({ message }) => message.value.id === newId,
})

// Generate new UUID and post to backend
const fetchPromise = fetch(`/api/items`, {
method: `POST`,
body: JSON.stringify({ uuid: newId }),
})

return await Promise.all([findUpdatePromise, fetchPromise])
}

async function clearItems() {
const itemsStream = getShapeStream<Item>(itemShape())
// Match the delete
const findUpdatePromise = matchStream({
stream: itemsStream,
operations: [`delete`],
// First delete will match
matchFn: () => true,
})
// Post to backend to delete everything
const fetchPromise = fetch(`/api/items`, {
method: `DELETE`,
})

return await Promise.all([findUpdatePromise, fetchPromise])
}

export default function Home() {
const { data: items } = useShape<Item>(itemShape())
const [optimisticItems, updateOptimisticItems] = useOptimistic<
Item[],
{ newId?: string; isClear?: boolean }
>(items, (state, { newId, isClear }) => {
if (isClear) {
return []
}

if (newId) {
// Merge data from shape & optimistic data from fetchers. This removes
// possible duplicates as there's a potential race condition where
// useShape updates from the stream slightly before the action has finished.
const itemsMap = new Map()
state.concat([{ id: newId }]).forEach((item) => {
itemsMap.set(item.id, { ...itemsMap.get(item.id), ...item })
})
return Array.from(itemsMap.values())
}

return []
})
)

return (
<div>
<form
action={async (formData: FormData) => {
const intent = formData.get(`intent`)
const newId = formData.get(`new-id`) as string
if (intent === `add`) {
updateOptimisticItems({ newId })
await createItem(newId)
} else if (intent === `clear`) {
updateOptimisticItems({ isClear: true })
await clearItems()
}
}}
>
<input type="hidden" name="new-id" value={uuidv4()} />
<button type="submit" className="button" name="intent" value="add">
Add
</button>
<button type="submit" className="button" name="intent" value="clear">
Clear
</button>
</form>
{optimisticItems.map((item: Item, index: number) => (
<p key={index} className="item">
<code>{item.id}</code>
</p>
))}
</div>
)
export default function Page() {
return <ClientItemsList />
}
7 changes: 7 additions & 0 deletions examples/nextjs/app/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Row } from "@electric-sql/client"

export interface Item extends Row {
id: string
value: string
[key: string]: string
}
2 changes: 1 addition & 1 deletion examples/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"backend:up": "PROJECT_NAME=nextjs-example pnpm -C ../../ run example-backend:up && pnpm db:migrate",
"backend:down": "PROJECT_NAME=nextjs-example pnpm -C ../../ run example-backend:down",
"db:migrate": "dotenv -e ../../.env.dev -- pnpm exec pg-migrations apply --directory ./db/migrations",
"dev": "next dev --turbo -p 5173",
"dev": "next dev --turbo -p 5174",
"build": "next build",
"start": "next start",
"format": "eslint . --fix",
Expand Down
6 changes: 5 additions & 1 deletion examples/remix/app/root.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import "./style.css"
import "./App.css"
import { ElectricProvider, ElectricScripts } from "@electric-sql/react"
import {
Links,
Meta,
Expand All @@ -18,7 +19,10 @@ export function Layout({ children }: { children: React.ReactNode }) {
<Links />
</head>
<body style={{ margin: 0, padding: 0 }}>
{children}
<ElectricProvider>
{children}
<ElectricScripts />
</ElectricProvider>
<ScrollRestoration />
<Scripts />
</body>
Expand Down
7 changes: 6 additions & 1 deletion examples/remix/app/routes/_index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import { useShape, preloadShape, getShapeStream } from "@electric-sql/react"
import { useFetchers, Form } from "@remix-run/react"
import { v4 as uuidv4 } from "uuid"
import type { ClientActionFunctionArgs } from "@remix-run/react"
import type { LoaderFunction } from "@remix-run/node"
import "../Example.css"
import { matchStream } from "../match-stream"

const itemShape = () => {
return {
url: new URL(`/shape-proxy`, window.location.origin).href,
url: import.meta.env.ELECTRIC_URL || `http://localhost:5173/shape-proxy`,
params: {
table: `items`,
},
Expand All @@ -16,6 +17,10 @@ const itemShape = () => {

type Item = { id: string }

export const loader: LoaderFunction = async () => {
return await preloadShape(itemShape())
}

export const clientLoader = async () => {
return await preloadShape(itemShape())
}
Expand Down
Loading
Loading