Manage the user-channel membership relation

Requires App Context

To set up and manage channel membership, you must enable App Context for your app's keyset in the Admin Portal.

When a user joins a channel or gets invited to it, a membership relation between that user and the channel is created (Membership entity). The membership ends when this user leaves the channel.

Read on to learn how to check and update user-channel membership.

Interactive demo

Check how a sample implementation could look like in a React app showcasing user-channel membership.

Want to implement something similar?

Read how to do that or go straight to the demo's source code.

Test it out

Choose whether you want to join or leave a given channel and wait until you get notified when that happens.

Get members

getMembers() returns the list of all channel members.

icon

Under the hood

Method signature

This method takes the following parameters:

channel.getMembers({
filter?: string,
sort?: object,
limit?: number,
page?: {
next?: string,
prev?: string,
}
}): Promise<{
page: {
next: string;
prev: string;
};
total: number;
status: number;
show all 17 lines

Input

ParameterTypeRequiredDefaultDescription
filterstringNon/aExpression used to filter the results. Returns only these members whose properties satisfy the given expression. The filter language is defined here.
sortobjectNon/aKey-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated. Use asc or desc to specify the sorting direction, or specify null to take the default sorting direction (ascending). For example: {name: "asc"}. By default, the items are sorted by the last updated date.
limitnumberNo100Number of objects to return in response. The default (and maximum) value is 100.
pageobjectNon/aObject used for pagination to define which previous or next result page you want to fetch.
 → nextstringNon/aRandom string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
 → prevstringNon/aRandom string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data. Ignored if the next parameter is supplied.

Output

ParameterTypeDescription
Promise<>objectReturned object containing these fields: page, total, status, and members.
 → pageobjectObject used for pagination to define which previous or next result page you want to fetch.
   → nextstringRandom string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
   → prevstringRandom string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data. Ignored if the next parameter is supplied.
 → totalnumberTotal number of channel members.
 → statusnumberStatus code of a server response, like 200.
 → membersMembership[]List of all related memberships.

Basic usage

List all members of the support channel on the premium support plan.

// reference the "channel" object
const channel = await chat.getChannel("support")

// get the list of all members with the premium support plan
await channel.getMembers({
filter: {"custom.support_plan == 'premium'"}
})

Get membership

getMemberships() returns the list of all channel memberships of a given user.

icon

Under the hood


To get a list of all existing channels, use the getChannels() method.

Method signature

This method takes the following parameters:

user.getMemberships({
filter?: string,
sort?: object,
limit?: number,
page?: {
next?: string,
prev?: string
}
}): Promise<{
page: {
next: string,
prev: string,
};
total: number,
status: number,
show all 17 lines

Input

ParameterTypeRequiredDefaultDescription
filterstringNon/aExpression used to filter the results. Returns only these memberships whose properties satisfy the given expression. The filter language is defined here.
sortobjectNon/aKey-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated. Use asc or desc to specify the sorting direction, or specify null to take the default sorting direction (ascending). For example: {name: "asc"}. By default, the items are sorted by the last updated date.
limitnumberNo100Number of objects to return in response. The default (and maximum) value is 100.
pageobjectNon/aObject used for pagination to define which previous or next result page you want to fetch.
 → nextstringNon/aRandom string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
 → prevstringNon/aRandom string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data. Ignored if the next parameter is supplied.

Output

ParameterTypeDescription
Promise<>objectReturned object containing these fields: page, total, status, and memberships.
 → pageanyObject used for pagination to define which previous or next result page you want to fetch.
 →  → nextstringRandom string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
 →  → prevstringRandom string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data. Ignored if the next parameter is supplied.
 → totalnumberTotal number of channel memberships.
 → statusnumberStatus code of a server response, like 200.
 → membershipsMembership[]List of all related memberships.

Basic usage

Find out which channels the support_agent_15 user is a member of.

// reference the "support_agent_15" user
const user = await chat.getUser("support_agent_15")

// get the list of all user memberships
await user.getMemberships()

Get updates

You can receive updates when specific user-channel Membership object(s) are added, edited, or removed using the following methods:

  • streamUpdates() checks updates on a single Membership object.
  • streamUpdatesOn() checks updates on a list of Membership objects.

Both methods accept a callback function as an argument. The Chat SDK invokes this callback whenever someone adds, changes, or removes membership data.

Underneath, these methods subscribe the current user to a channel and add an objects event listener to receive all objects events of type membership. These methods also return the unsubscribe function you can invoke to stop receiving objects events and unsubscribe from the channel.

icon

Under the hood

Method signature

These methods take the following parameters:

  • streamUpdates()

    membership.streamUpdates(
    callback: (membership: Membership) => unknown
    ): () => void
  • streamUpdatesOn()

    static Membership.streamUpdatesOn(
    memberships: Membership[],
    callback: (memberships: Membership[]) => unknown
    ): () => void

Input

ParameterTypeRequired in streamUpdates()Required in streamUpdatesOn()DefaultDescription
membershipsMembership[]NoYesn/aArray of Membership objects for which you want to get updates.
callbackn/aYesYesn/aCallback function passed as a parameter to both methods. It defines the custom behavior to be executed when detecting membership changes.
 → membershipMembershipYesNon/aReturned Membership object with the updated data.
 → membershipsMembership[]NoYesn/aReturned array of Membership objects with the updated data.

Output

TypeDescription
() => voidFunction you can call to disconnect (unsubscribe) from the channel and stop receiving objects events.

Errors

Whenever a list of Membership objects is required as a parameter, and you try to get updates on membership without specifying their list, you will receive the Cannot stream membership updates on an empty list error.

Basic usage

Get updates on the first user membership.

  • streamUpdates()

    const { memberships } = await chat.currentUser.getMemberships()
    const membership = memberships[0]
    membership.streamUpdates((membership) => {
    console.log("Updated membership: ", membership)
    })

Get updates on the first page of user memberships.

  • streamUpdatesOn()

    const { memberships } = await chat.currentUser.getMemberships()
    Membership.streamUpdatesOn(memberships, (memberships) => {
    console.log("Updated memberships: ", memberships)
    })

Other examples

Stop listening to updates on the first user membership.

  • streamUpdates()

    const { memberships } = await chat.currentUser.getMemberships()
    const membership = memberships[0]
    const stopUpdates = membership.streamUpdates(/* handle update callback */)
    // after some time...
    stopUpdates()

Stop listening to updates on the first page of user memberships.

  • streamUpdatesOn()

    const { memberships } = await chat.currentUser.getMemberships()
    const stopUpdates = Membership.streamUpdatesOn(memberships, /* handle update callback */)
    // after some time...
    stopUpdates()

Update

update() updates the channel membership information for a given user.

icon

Under the hood

Method signature

This method takes the following parameters:

membership.update({
custom: ObjectCustom
}): Promise<Membership>

Input

ParameterTypeRequiredDefaultDescription
customObjectCustomYesn/aAny custom properties or metadata associated with the channel-user membership.

Output

TypeDescription
Promise<Membership>Returned (modified) object containing all membership data.

Errors

If you try to update a membership that doesn't exist, you will receive the No such membership exists error.

Basic usage

Assign the premium-support role to support_agent_15 on the high-priority-incidents channel.

// reference the "support_agent_15" user
const user = await chat.getUser("support_agent_15")

// get the list of all user memberships and filter out the right channel
const membership = await user.getMemberships({
filter: "channel.id == 'high-priority-incidents'"
})

// add custom metadata to the user membership
await membership.update({
custom: {role: "premium-support"}
})
Last updated on