Skip to content

Commit

Permalink
Restore old look & fix optimistic updates
Browse files Browse the repository at this point in the history
  • Loading branch information
KyleAMathews committed Jan 17, 2025
1 parent a2a96a7 commit 73676da
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 21 deletions.
46 changes: 31 additions & 15 deletions examples/nextjs/app/items-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,28 +50,44 @@ async function clearItems() {
export function ItemsList() {
const shapeOptions = getClientShapeOptions()
const { data: rows } = useShape<Item>(shapeOptions)
console.log({ rows })
const [optimisticItems, addOptimisticItem] = useOptimistic(
rows,
(state, newItem: Item) => [...state, newItem]
)
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()
const value = `Item ${id.slice(0, 4)}`
startTransition(() => {
addOptimisticItem({ id, value })
})
try {
startTransition(async () => {
updateOptimisticItems({ newId: id })
await createItem(id)
} catch (error) {
console.error('Failed to create item:', error)
// You might want to add error handling here to revert the optimistic update
}
})
}

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

return (
Expand Down
21 changes: 15 additions & 6 deletions examples/nextjs/app/items-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,26 @@ export function ItemsView({ items, onAdd, onClear }: ItemsViewProps) {
console.log({ items })
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) => (
<div key={item.id} className="item">
<p key={item.id} className="item">
{item.id}
</div>
</p>
))}
</div>
<div className="buttons">
{onAdd && <button onClick={onAdd}>Add Item</button>}
{onClear && <button onClick={onClear}>Clear Items</button>}
</div>
</div>
)
}

0 comments on commit 73676da

Please sign in to comment.