Skip to content

useSWRSubscription does not work with async subscribe function #4214

@sarioglu

Description

@sarioglu

Bug report

Description / Observed Behavior

useSWRSubscription accepts an async subscribe function as per TypeScript types but does not await it and therefore does not subscribe properly. In addition, if the subscribe function is marked as async, it cannot get returned unsubscribe function as it's wrapped in a Promise.

I encountered this while trying to connect to an AWS Amplify event source. See following code example below for an example.

Expected Behavior

It should either await async subscribe function (which is preferred) or do not accept one.

Repro Steps / Code Example

import { events } from "aws-amplify/data";

const useSubscribeToEventSource = () => {
  return useSWRSubscription(key, async (_key, { next }) => {
    // .connect function is async
    const channel  = await events.connect("channel-name");
    const subscription = channel.subscribe({
      next: event => next(null, event),
      error: error => next(error, null)
    });

    return () => {
      try {
        subscription?.unsubscribe();
      } finally {
        channelRef.current?.close();
      }
    };
  });
};

Additional Context

SWR version: 2.3.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions