Last active
March 7, 2025 18:38
-
-
Save chrisoverstreet/ab267cb25e5da0aab1d4a71a043a3bec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
useSubscription<OnUpdateEventGuestSubscription, OnUpdateEventGuestSubscriptionVariables>({ | |
query: OnUpdateEventGuestDocument, | |
variables: { eventId: eventId ?? '' }, | |
next: ({ data }) => { | |
const { onUpdateEventGuest: guest } = data; | |
if (guest) { | |
updateEventGuest(guest); | |
} | |
}, | |
pause: !eventId, | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { GraphQLOptionsV6, GraphqlSubscriptionMessage, GraphqlSubscriptionResult } from '@aws-amplify/api-graphql'; | |
import type { DocumentNode } from 'graphql/index'; | |
import { useEffect, useRef } from 'react'; | |
import { useCreateAmplifySubscription } from '@/clients/amplify'; | |
type Subscription = ReturnType<Awaited<ReturnType<ReturnType<typeof useCreateAmplifySubscription>>>['subscribe']>; | |
export default function useSubscription<T, V extends GraphQLOptionsV6<T, string>['variables']>({ | |
query, | |
variables, | |
pause, | |
next, | |
}: { | |
query: DocumentNode; | |
variables: V; | |
pause?: boolean; | |
next: (message: GraphqlSubscriptionMessage<T>) => void; | |
}) { | |
const createAmplifySubscription = useCreateAmplifySubscription(); | |
const subscriptionResultPromiseRef = useRef<Promise<GraphqlSubscriptionResult<T>>>(); | |
useEffect(() => { | |
let subscription: Subscription; | |
if (subscriptionResultPromiseRef.current) { | |
return; | |
} | |
if (!pause) { | |
(async () => { | |
subscriptionResultPromiseRef.current = createAmplifySubscription(query, variables); | |
subscription = (await subscriptionResultPromiseRef.current).subscribe({ | |
// error: console.log, | |
next, | |
}); | |
})(); | |
} | |
return () => { | |
subscription?.unsubscribe(); | |
}; | |
}, [createAmplifySubscription, next, pause, query, variables]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment