Skip to content

Commit

Permalink
Refactor onMount/onUnmount functions in usePresence hook
Browse files Browse the repository at this point in the history
  • Loading branch information
VeskeR committed Mar 12, 2024
1 parent dfa04b5 commit a1aba5a
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions src/platform/react-hooks/src/hooks/usePresence.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type * as Ably from 'ably';
import { useCallback, useEffect } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';

Check warning on line 2 in src/platform/react-hooks/src/hooks/usePresence.ts

View workflow job for this annotation

GitHub Actions / lint

'useMemo' is defined but never used

Check warning on line 2 in src/platform/react-hooks/src/hooks/usePresence.ts

View workflow job for this annotation

GitHub Actions / lint

'useRef' is defined but never used

Check warning on line 2 in src/platform/react-hooks/src/hooks/usePresence.ts

View workflow job for this annotation

GitHub Actions / lint

'useState' is defined but never used
import { ChannelParameters } from '../AblyReactHooks.js';
import { useAbly } from './useAbly.js';
import { useChannelInstance } from './useChannelInstance.js';
Expand Down Expand Up @@ -27,26 +27,29 @@ export function usePresence<T = any>(
const { channel } = useChannelInstance(params.ablyId, params.channelName);
const { connectionError, channelError } = useStateErrors(params);

const onMount = async () => {
const onMount = useCallback(async () => {
await channel.presence.enter(messageOrPresenceObject);
};
// don't add messageOrPresenceObject to dependency list, since it will most likely cause an infinite loop of updates,
// in cases when user calls this hook with an object literal instead of a state or memoized object.
// it does however prevent us from re-entering presence with new data automatically if it changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [channel.presence]);

const onUnmount = () => {
const onUnmount = useCallback(() => {
// if connection is in one of inactive states, leave call will produce exception
if (channel.state === 'attached' && !INACTIVE_CONNECTION_STATES.includes(ably.connection.state)) {
channel.presence.leave();
}
};
}, [channel, ably.connection.state]);

const useEffectHook = () => {
if (!skip) onMount();
useEffect(() => {
if (skip) return;

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

// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(useEffectHook, [skip]);
}, [skip, onMount, onUnmount]);

const updateStatus = useCallback(
(messageOrPresenceObject: T) => {
Expand Down

0 comments on commit a1aba5a

Please sign in to comment.