Skip to content

Commit

Permalink
✨ unsubscribe from channel on effect cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Harley Alexander authored and Harley Alexander committed Jun 4, 2020
1 parent 4761391 commit 2680446
Show file tree
Hide file tree
Showing 4 changed files with 1,571 additions and 981 deletions.
21 changes: 20 additions & 1 deletion src/__tests__/useChannel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe("useChannel()", () => {
<__PusherContext.Provider value={{ client: undefined }} {...props} />
);
const { result } = renderHook(() => useChannel("public-channel"), {
wrapper
wrapper,
});

expect(result.current).toBeUndefined();
Expand All @@ -32,4 +32,23 @@ describe("useChannel()", () => {
);
expect(result.current).toBeInstanceOf(PusherChannelMock);
});

test("should unsubscribe on unmount", async () => {
const mockUnsubscribe = jest.fn();
const client = {
subscribe: jest.fn(),
unsubscribe: mockUnsubscribe,
};
const wrapper = ({ children }) => (
<__PusherContext.Provider value={{ client: client as any }}>
{children}
</__PusherContext.Provider>
);
const { unmount } = await renderHook(() => useChannel("public-channel"), {
wrapper,
});
unmount();

expect(mockUnsubscribe).toHaveBeenCalled();
});
});
3 changes: 2 additions & 1 deletion src/testUtils.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { act, renderHook } from "@testing-library/react-hooks";
import { renderHook } from "@testing-library/react-hooks";
import { act } from "react-dom/test-utils";

import Pusher from "pusher-js";
import { PusherMock } from "pusher-js-mock";
Expand Down
9 changes: 8 additions & 1 deletion src/useChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,18 @@ export function useChannel<T extends Channel & PresenceChannel>(
const { client } = usePusher();
const [channel, setChannel] = useState<T | undefined>();
useEffect(() => {
/** Return early if there's no client */
if (!client) return;
const pusherChannel = client?.subscribe(channelName);

/** Subscribe to channel and set it in state */
const pusherChannel = client?.subscribe(channelName);
setChannel(pusherChannel as T);

/** Cleanup on unmount/re-render */
return () => client?.unsubscribe(channelName);
}, [channelName, client]);

/** Return the channel for use. */
return channel;
}

Expand Down

0 comments on commit 2680446

Please sign in to comment.