useChannelMessage

useChannelMessage(channelId: string, eventName: string, listener: Function): void

You can use this hook to subscribe to Channel message events in your React app.

Example

This example assumes you have already initialized the Hop React SDK.

import { useChannelMessage } from "@onehop/react";

const channelId = "group_chat";

export default function MyComponent() {
  const [chatMessages, setChatMessages] = useState([]);

  // in this example, USER_MESSAGE is an event that you'd send to the channel from your backend
  useChannelMessage(channelId, "USER_MESSAGE", (message) => {
    // this will be called every time the USER_MESSAGE event is sent to this channel
    setChatMessages((m) => [...m, message]);
  });

  return (
    <ul>
      {chatMessages.map((m) => (
        <li>
          <b>{m.author}</b>: {m.content}
        </li>
      ))}
    </ul>
  );
}

useReadChannelState

useReadChannelState(channelId: string): ChannelStateData

You can use this hook to subscribe to Channel state in your React app.

Hook Return Value

fieldtypedescription
state?objectthe channel state
error?objectleap error (if failed to subscribe)
subscriptionenumnon_existent, pending, unavailable, or available

Example

This example assumes you have already initialized the Hop React SDK.

import { useReadChannelState } from "@onehop/react";

const channelId = "weather";

export default function MyComponent() {
  const { state } = useReadChannelState(channelId);

  // state is null until the client has connected to the channel
  if (!state) {
    return <p>Loading...</p>;
  }

  return <p>Temperature in London: {state.london?.temperature}</p>;
}