There are multiple places you could handle your Ably channel subscriptions


1. In a component that reacts to Ably messages.

2. Somewhere globally in the app, that then passes messages onwards via state management, props, or some other mechanism.


An example component can be seen below or in this gist:


import React from 'react'
import Ably from "ably/promises";

const client = new Ably.Realtime("your-ably-api-key");

export default class AblyMessageComponent extends React.Component {
  
  constructor() {
    super();
    this.state = { messages: [] };
  }

  async componentDidMount() {
    this.channel = await client.channels.get("my-cool-channel");
    
    await this.channel.subscribe(message => {
      console.log("A message was received", message);

      this.state.messages.push(message.data.text);
      this.setState({ messages: this.state.messages });
    });

    console.log("You are subscribed");
  }

  async componentWillUnmount() {
    this.channel.unsubscribe();

    console.log("You are unsubscribed");
  } 
  
  sendMessage() {
    this.channel.publish({ name: "myEventName", data: { text: "Some random stuff here." } })
  }

  render() {
    return (
      <main>
        <button onClick={ (e) => this.sendMessage(e) }>Click here to send a message</button>
        <h2>Messages will appear here:</h2>
        <ul> 
          {this.state.messages.map((text, index) => (<li key={"item" + index}>{text}</li>))}
        </ul>
      </main>
    )
  }
}


  • The Ably client is created outside of the scope of the component and used inside of it.
  • State is set up in the constructor
  • Get the Ably channel in the componentDidMount() function.
  • Subscribe in componentDidMount()
  • Make sure to unsubscribe in componentWillUnmount()
  • Click handler on a button will publish new messages


Why this specific setup is important:


The Ably channel needs to remain connected while the component is visible and mounted in your application. By creating channel subscriptions during componentDidMount()you make sure that the Ably client connects and disconnects appropriately as the component is toggled on or off.


In addition - making sure that you unsubscribe during componentWillUnmount() prevents you from using up Ably connections against your connection limit, while your users cannot interact with the component.


If you need multiple components to react to Ably messages, you will need to manage this subscription and cascade the received messages in another way, probably from a parent component passing the received message data as props, or using your own state management solution.


Please note - the above example uses the Ably API key in the constructor call to Ably.Realtime. In a production scenario, you should use Token Authentication instead, as putting your Ably API key directly into your React JSX markup exposes your API key to theft and abuse.