Hooks

View as Markdown

Hooks are functions that you can call inside theme components to access data. When the data changes, the component will automatically re-render with the new data.

Here's an example component that lists the names of up to 10 participants in a conversation.

1import { html, useParticipants } from "@talkjs/react-components";
2
3export function MyComponent({ common }) {
4 const participants = useParticipants(common.conversation.id, 10);
5
6 return html`<div>
7 ${participants.map(p => html`<span key=${p.user.id}>${p.user.name}</span>`)}
8 </div>`;
9}

useParticipants

useParticipants(conversationId, limit): ParticipantSnapshot[]

Returns a list of participants in the conversation with the given ID. It'll initially return an empty list, and re-render the calling component as data participants are loaded. It'll also cause a re-render when any of those participants change, such as when a user's name or photoUrl changes.

Parameters

conversationId
: string

ID of the conversation

limit (optional)
: number

Maximum number of participants to subscribe to. Defaults to 10. The maximum is 100.

Returns

ParticipantSnapshot[]

List of participant snapshots.

useReactions

useReactions(conversationId, messageId, emoji): [SingleReactionSnapshot[], () => void]

Returns a tuple of reaction snapshots for the given emoji, and a function that populates this data.

This hook lets you lazy-load up to 10 users that first sent the specified emoji reaction. It's designed to let you display this information just-in-time, in eg a tooltip or popover.

You can safely call the load function multiple times without causing needless extra fetches.

Parameters

conversationId
: string

ID of the conversation

messageId
: string

ID of the message

emoji
: string

emoji (as a unicode string) for which you want to load all reactions

Returns

[SingleReactionSnapshot[], () => void]

A tuple of a SingleReactionSnapshot array and a subscribe function.

Usage

Example
1const [reactions, subscribe] = useReactions(conversationId, message.id, emoji);
2return (
3 <div
4 onMouseOver={subscribe}
5 title={reactions?.map((r) => r.user.name).join(", ")}
6 >
7 {emoji}
8 </div>
9);