Slide 34
Slide 34 text
データの更新(update)、データの削除(delete)をリアルタイムで反映させる
supabase.channel('todos-channel')
.on(
'postgres_changes',
{ event: 'INSERT', schema: 'public', table: 'todos' },
(payload) => {
setTodos((prev) => [payload.new, ...prev])
}
)
.on(
'postgres_changes',
{ event: 'UPDATE', schema: 'public', table: 'todos' },
(payload) => {
setTodos((prev) => {
const updatedTodo = payload.new
const targetIndex = prev.findIndex(
(todo) => todo.id === updatedTodo.id
)
if (targetIndex >= 0) {
prev[targetIndex] = updatedTodo
}
return [...prev]
})
}
)
.on('postgres_changes',
{ event: 'DELETE', schema: 'public', table: 'todos' },
(payload) => {
setTodos((prev) =>
prev.filter((todo) => todo.id !== payload.old.id)
)
}
).subscribe()
【Supabase×React】サーバレスアプリ開発入門
34