Reactions
Emoji reactions and up or down votes on any subject, messages (comments included) and inbox messages, with custom emoji per organization, counts under each subject's read rules and a realtime topic per organization.
reactions stores one row per actor and emoji on a subject. A member reacts to a subject they can read; counts, whether the user reacted and the first actors come back in one call. Reading needs reactions.read, reacting needs reactions.create, and custom emoji need reactions.manage.
better-supabase add reactionsThe block's entity is reaction (the reactions table). It isn't registered as a subject. Rename it with blocks.reactions.names.
Server code calls the reactions instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useReactions } = defineDataHooks(
"reactions",
(db: AppDb) => db.reactions,
);import { createReactions } from "better-supabase/blocks/reactions";
const doc = { type: "doc", id: docId };
await db.reactions.react(doc, "👍").orThrow();
const byDoc = await db.reactions
.summary(docIds.map((id) => ({ type: "doc", id })))
.orThrow();
byDoc[`doc:${docId}`]; // the doc's ReactionCount[]
await db.reactions.react(doc, "👍", { present: false }).orThrow();"use client";
import { useReactions } from "@/lib/supabase/hooks";
const rows = useReactions({ limit: 50 });Every call acts in the block's tenant, an organization id or a function that returns the current one; createBlocks and createBlockClient pass the request's tenant, and a call without one fails with invalid_request and the hint TENANT_REQUIRED. A subject is a RecordRef, { type, id }. summary(subjects) takes up to 200 subjects of each type and returns their reactions keyed type:id (subjectKey(subject) from better-supabase/blocks); a subject without reactions may be left out.
react returns the subject's reactions, most used first:
| Field | What it holds |
|---|---|
emoji | The emoji, or a custom emoji's :shortcode: |
count | How many actors reacted with it |
reacted | Whether the signed-in user is one of them |
actors | The first ten actors: user ids, or names the service passed |
Subjects
A reaction's subject is any config.recordTypes type, or a message (with the messaging module, which includes comments and the inbox). Messages are always included, under the message entity's name (message, or the name blocks.messaging.names.message sets), even when on lists other types. react and the read policy check that the caller sees the subject: the functions run as the caller, so the subject table's own policies apply, and the caller also needs the subject's read permission (messages.read for a message). A subject with a deletedAt column, such as a message, must not be deleted. Without registry subjects every type is accepted for members of the organization.
The service role reacts for anyone and passes the actor's name:
await reactions
.react({ type: "message", id: commentId }, "✅", { actor: "deploy-bot" })
.orThrow();who({ subject, emoji? }) lists the actors behind each emoji for a "who reacted" popover. The database returns the first ten actors per emoji, and hidden counts the rest. It follows the same read rules as summary.
const byEmoji = await reactions.who({ subject }).orThrow();
// { "👍": { actors: [...], hidden: 3 } }Votes
A vote is a reaction with kind: "vote": up (1) or down (-1), one per actor and subject. vote(subject, value) sets the caller's vote, 0 clears it, and voting the other way switches it. It needs the same permissions as react and returns the subject's tally:
const tally = await reactions.vote({ type: "idea", id: ideaId }, 1).orThrow();
// { score: 12, up: 15, down: 3, vote: 1 }
const byIdea = await reactions
.votes(ideaIds.map((id) => ({ type: "idea", id })))
.orThrow();
byIdea[`idea:${ideaId}`]; // the idea's VoteTallyvotes(subjects) reads up to 200 subjects of each type, keyed type:id; a subject without votes may be left out. vote is the caller's own vote, 0 when they haven't voted. The tally lives in the reaction_scores table, which a trigger keeps current and which the subject's read rules guard, so you can sort a list by score in SQL. summary() stays emoji-only, and a scores model can count a record's vote score as a metric.
Inbox messages
Inbox messages are messages too: inbox.messages.react() calls react_to_inbox_message, which applies the inbox's rules (a contact reacts on their own conversation, staff with inbox.reply on notes) and stores the reaction on the message subject in this table. react({ type: "message", id }) on an inbox message applies the messaging rules instead.
Custom emoji
An organization's custom emoji are shortcodes with an image: an attachment id from attachments or an https:// URL. A reaction :shortcode: must name one of them, or react fails with REACTION_INVALID. Deleting a custom emoji deletes the reactions that used it.
await reactions
.saveCustomEmoji({
shortcode: "ship-it",
url: "https://cdn.example.com/ship-it.png",
})
.orThrow();
const emoji = await reactions.customEmoji().orThrow();Realtime
Every change broadcasts changed with the subjectType and subjectId to reactions:{organizationId} (options.topic renames the prefix). Members with reactions.read can join it. useReactions is a registry item: npx shadcn add @better-supabase/use-reactions writes hooks/use-reactions.ts into the app. The hook loads the subjects on screen and loads them again when one of them changes. It reads the schema and the topic from the blocks config passed to the browser client (createClient(betterSupabase, { blocks: blockConfig })), so topic is only needed to override it (null loads without listening), and it acts in the client's tenant: the client's organization option, then the session's organization claim. It waits while there is no tenant.
import { useReactions } from "@/hooks/use-reactions";
const { reactions, toggle } = useReactions({
subjects: comments.map((comment) => ({ type: "message", id: comment.id })),
});
await toggle({ type: "message", id: commentId }, "🎉");reactions is keyed type:id, like summary. When the subjects on screen change, the hook loads the new ones without building a new controller.
Vue
useBlockController from better-supabase/vue runs
createReactionsController with its options: a client built with its tenant, the
same tenant for the topic, subjects and an optional topic; auth and ports come from
app.use(betterSupabase(bsb)) unless you pass them. state is a shallow ref
of the snapshot and actions are the controller's actions. The work starts
on mount, and the controller is disposed with the component.
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import {
createReactions,
createReactionsController,
rpcTransport,
} from "better-supabase/blocks/reactions";
const { organizationId, commentIds } = defineProps<{
organizationId: string;
commentIds: string[];
}>();
const supabase = useSupabase();
const { state, actions } = useBlockController(createReactionsController, {
client: createReactions({
transport: rpcTransport(supabase),
tenant: organizationId,
}),
tenant: organizationId,
subjects: commentIds.map((id) => ({ type: "message", id })),
});
</script>
<template>
<p>{{ Object.keys(state.reactions ?? {}).length }}</p>
<button @click="actions.refresh()">Refresh</button>
</template>Svelte
useBlockController from better-supabase/svelte runs
createReactionsController with its options; auth and ports come from
setBetterSupabase(bsb) unless you pass them. It returns a readable
store of the snapshot, read with $, with the actions on .actions. The
work starts on mount, and the controller is disposed with the component.
<script lang="ts">
import { betterSupabase, useBlockController } from "better-supabase/svelte";
import {
createReactions,
createReactionsController,
rpcTransport,
} from "better-supabase/blocks/reactions";
let { organizationId, commentIds }: { organizationId: string; commentIds: string[] } = $props();
const { supabase } = betterSupabase();
const reactions = useBlockController(createReactionsController, {
client: createReactions({
transport: rpcTransport(supabase),
tenant: organizationId,
}),
tenant: organizationId,
subjects: commentIds.map((id) => ({ type: "message", id })),
});
</script>
<p>{Object.keys($reactions.reactions ?? {}).length}</p>
<button onclick={() => reactions.actions.refresh()}>Refresh</button>Solid
useBlockController from better-supabase/solid runs
createReactionsController with its options; auth and ports come from
<BetterSupabaseProvider client={bsb}> unless you pass them. state() reads
the snapshot through from, and actions are the controller's actions. The
work starts on mount, and the controller is disposed with the owner.
import { useBlockController, useSupabase } from "better-supabase/solid";
import {
createReactions,
createReactionsController,
rpcTransport,
} from "better-supabase/blocks/reactions";
export function Component(props: {
organizationId: string;
commentIds: string[];
}) {
const supabase = useSupabase();
const { state, actions } = useBlockController(createReactionsController, {
client: createReactions({
transport: rpcTransport(supabase),
tenant: props.organizationId,
}),
tenant: props.organizationId,
subjects: props.commentIds.map((id) => ({ type: "message", id })),
});
return (
<>
<p>{Object.keys(state().reactions ?? {}).length}</p>
<button onClick={() => actions.refresh()}>Refresh</button>
</>
);
}Events and hooks
The module records reaction.added and reaction.deleted with organizationId, subjectType, subjectId, emoji, actor, kind (emoji or vote) and, for a vote, value. A consumer that only wants emoji reactions filters on kind. react calls the before_react and after_react SQL hooks with the tenant, subject type, subject id, emoji and whether the reaction is added.
| Error | When |
|---|---|
REACTION_FORBIDDEN | The caller lacks the permission or can't see the subject |
REACTION_INVALID | The emoji is empty, longer than 64 characters, has spaces or is unknown, or a vote isn't -1, 0 or 1 |
With ReUI
Render the ReUI Emoji Picker for new reactions and one Bubble per ReactionCount, highlighted when reacted is true. toggle(subject, emoji) adds the emoji, or removes it when the user already reacted with it.
Without the client
db.reactions is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createReactions } from "better-supabase/blocks/reactions";
const reactions = createReactions({ transport, tenant: organizationId });
const doc = { type: "doc", id: docId };
await reactions.react(doc, "👍").orThrow();
const byDoc = await reactions
.summary(docIds.map((id) => ({ type: "doc", id })))
.orThrow();
byDoc[`doc:${docId}`]; // the doc's ReactionCount[]
await reactions.react(doc, "👍", { present: false }).orThrow();Toggle a reaction
toggle({ subject, emoji }) adds the caller's reaction, or removes it when they already reacted with that emoji, and returns the counts.
Last updated on