Skip to content
This repository has been archived by the owner on Oct 30, 2023. It is now read-only.

Commit

Permalink
Merge pull request #85 from ably-labs/optional-msg-callback-2
Browse files Browse the repository at this point in the history
feat: allow useChannel without message callback
  • Loading branch information
owenpearson authored Aug 30, 2023
2 parents 0ae21ab + 9063283 commit 60f11e6
Showing 1 changed file with 21 additions and 13 deletions.
34 changes: 21 additions & 13 deletions src/hooks/useChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ type SubscribeArgs = [string, AblyMessageCallback] | [AblyMessageCallback];

export function useChannel(
channelNameOrNameAndOptions: ChannelParameters,
callbackOnMessage: AblyMessageCallback
callbackOnMessage?: AblyMessageCallback
): ChannelResult;
export function useChannel(
channelNameOrNameAndOptions: ChannelParameters,
event: string,
callbackOnMessage: AblyMessageCallback
callbackOnMessage?: AblyMessageCallback
): ChannelResult;

export function useChannel(
channelNameOrNameAndOptions: ChannelParameters,
eventOrCallback: string | AblyMessageCallback,
eventOrCallback?: string | AblyMessageCallback,
callback?: AblyMessageCallback
): ChannelResult {
const channelHookOptions =
Expand Down Expand Up @@ -67,20 +67,28 @@ export function useChannel(
}, [ablyMessageCallback]);

useEffect(() => {
const listener: AblyMessageCallback = (message) => {
ablyMessageCallbackRef.current &&
ablyMessageCallbackRef.current(message);
};

const subscribeArgs: SubscribeArgs =
channelEvent === null ? [listener] : [channelEvent, listener];

if (!skip) {
const listener: AblyMessageCallback | null =
ablyMessageCallbackRef.current
? (message) => {
ablyMessageCallbackRef.current &&
ablyMessageCallbackRef.current(message);
}
: null;

const subscribeArgs: SubscribeArgs | null = listener
? channelEvent === null
? [listener]
: [channelEvent, listener]
: null;

if (!skip && subscribeArgs) {
handleChannelMount(channel, ...subscribeArgs);
}

return () => {
!skip && handleChannelUnmount(channel, ...subscribeArgs);
!skip &&
subscribeArgs &&
handleChannelUnmount(channel, ...subscribeArgs);
};
}, [channelEvent, channel, skip]);

Expand Down

0 comments on commit 60f11e6

Please sign in to comment.