Skip to content

WebSocket

Introduction

Websockets allow you to subscribe to a threadId and receive updates for new messsages. Here is how you can add them to your application.

Step 1 - Install Dependencies.

yarn add ably

Step 2 - Setup your code.

Let's create a file that'll have our React hook named Ably.js.

import Ably from "ably/promises";
import { useEffect } from 'react'

const ably = new Ably.Realtime.Promise({ authUrl: 'https://theconvo.space/api/getAblyAuth?apikey=CONVO' });

export function useChannel(channelName, callbackOnMessage) {
    const channel = ably.channels.get(channelName);

    const onMount = () => {
        channel.subscribe(msg => { callbackOnMessage(msg); });
    }

    const onUnmount = () => {
        channel.unsubscribe();
    }

    const useEffectHook = () => {
        onMount();
        return () => { onUnmount(); };
    };

    useEffect(useEffectHook);

    return [channel, ably];
}

Step 3 - Subscribe to a Channel.

import { useChannel } from "@/hooks/Ably";

// the threadId you want to track.
const threadId = "KIGZUnR4RzXDFheXoOwo"
const [channel, ably] = useChannel(threadId, (newMessage) => {
    // Function called when a new message comes in.
    console.log(newMessage);
});


Comments