Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Amplify Gen2] How to Set up a real-time event subscription?? #2693

Closed
ggj0418 opened this issue Jul 8, 2024 · 4 comments
Closed

[Amplify Gen2] How to Set up a real-time event subscription?? #2693

ggj0418 opened this issue Jul 8, 2024 · 4 comments
Labels
pending-triage question Further information is requested

Comments

@ggj0418
Copy link

ggj0418 commented Jul 8, 2024

Amplify CLI Version

1.1.0 (npx ampx --version)

Question

To set up a real-time event subscription, i referred to this document

And this is my code.

// {root}/event/orderEventListener.ts
'use client'

import { CONNECTION_STATE_CHANGE, ConnectionState } from 'aws-amplify/data'
import { Hub } from 'aws-amplify/utils'
import { generateClient } from 'aws-amplify/api'
import { Schema } from '@/amplify/data/resource'

const userClient = generateClient<Schema>()

// @ts-ignore FIXME: Expression produces a union type that is too complex to represent.
userClient.models.Order.onUpdate().subscribe({
  next: (data) => console.log(`Order updated: ${JSON.stringify(data, null, 2)}`),
  error: (error) => console.warn(error)
})

// @ts-ignore FIXME: Expression produces a union type that is too complex to represent.
userClient.models.Order.onCreate().subscribe({
  next: (data) => console.log(`Order created: ${JSON.stringify(data, null, 2)}`),
  error: (error) => console.warn(error)
})

Hub.listen('api', (data: any) => {
  const { payload } = data
  if (payload.event === CONNECTION_STATE_CHANGE) {
    console.log(`API hub payload is ${payload}`)
    const connectionState = payload.data.connectionState as ConnectionState
    console.log(connectionState)
  }
})

But, when i created a new order data with that userClient on the client side, above onCreate()method or Hub.listen method was not remained any logs.

How should I set up the real-time event subscription?

@ggj0418 ggj0418 added pending-triage question Further information is requested labels Jul 8, 2024
@ggj0418
Copy link
Author

ggj0418 commented Jul 8, 2024

I tried to inject that subscription part to React's Context Provider. Then, the Hub.listen starts to remain logs. But the OnCreate() and OnUpdate() method is still not working

'use client'

import { createContext, FC, ReactNode, useLayoutEffect } from 'react'
import { userClient } from '@/utils/generateClient/userClient'
import { Hub } from 'aws-amplify/utils'
import { CONNECTION_STATE_CHANGE, ConnectionState } from 'aws-amplify/api'

interface OrderEventProps {
}

const OrderEvent = createContext<OrderEventProps | undefined>(undefined)

interface OrderEventListenerProviderProps {
  children: ReactNode
}

export const OrderEventListenerProvider: FC<OrderEventListenerProviderProps> = ({ children }) => {
  useLayoutEffect(() => {
    // @ts-ignore FIXME: Expression produces a union type that is too complex to represent.
    const orderEventUnsubscribe = userClient.models.Order.onUpdate().subscribe({
      next: (data) => console.log(`Order updated: ${JSON.stringify(data, null, 2)}`),
      error: (error) => console.warn(`Order update error: ${error}`)
    })

    return () => {
      orderEventUnsubscribe.unsubscribe()
    }
  }, [])

  useLayoutEffect(() => {
    // @ts-ignore FIXME: Expression produces a union type that is too complex to represent.
    const orderEventUnsubscribe = userClient.models.Order.onCreate().subscribe({
      next: (data) => console.log(`Order created: ${JSON.stringify(data, null, 2)}`),
      error: (error) => console.warn(`Order create error: ${error}`)
    })

    return () => {
      orderEventUnsubscribe.unsubscribe()
    }
  }, [])

  useLayoutEffect(() => {
    const hubDataUnsubscribe = Hub.listen('api', (data: any) => {
      const { payload } = data
      console.log(`API hub data is ${payload}`)
      if (payload.event === CONNECTION_STATE_CHANGE) {
        const connectionState = payload.data.connectionState as ConnectionState
        console.log(connectionState)
      }
    })

    return () => {
      hubDataUnsubscribe()
    }
  }, [])

  return <OrderEvent.Provider value={undefined}>{children}</OrderEvent.Provider>
}

@ggj0418
Copy link
Author

ggj0418 commented Jul 8, 2024

I also did this trial, but have this error messge.

import { generateClient } from 'aws-amplify/api'
import { Schema } from '@/amplify/data/resource'

export const userClient = generateClient<Schema>({ authMode: 'userPool' })

const createSub = userClient.models.Order.onCreate().subscribe({
  next: (data) => console.log(`Order created: ${JSON.stringify(data, null, 2)}`),
  error: (error) => console.warn(`Order create error: ${error}`)
})

const updateSub = userClient.models.Order.onUpdate().subscribe({
  next: (data) => console.log(`Order updated: ${JSON.stringify(data, null, 2)}`),
  error: (error) => console.warn(`Order update error: ${error}`)
})
Error: Client could not be generated. This is likely due to `Amplify.configure()` not being called prior to `generateClient()` or because the configuration passed to `Amplify.configure()` is missing GraphQL provider configuration.

@ggj0418
Copy link
Author

ggj0418 commented Jul 8, 2024

Oh I re-location the declaration of subscription method like this and it well-works.

Amplify.configure(config, { ssr: true })

export default function ConfigureAmplifyClientSide() {
  useEffect(() => {
    // @ts-ignore FIXME: Expression produces a union type that is too complex to represent.
    const subOrderEvent = userClient.models.Order.onCreate().subscribe({
      next: (data) => console.log(`Order created: ${JSON.stringify(data, null, 2)}`),
      error: (error) => console.warn(`Order create error: ${JSON.stringify(error, null, 2)}`)
    })

    return () => {
      subOrderEvent.unsubscribe()
    }
  }, [])

  return null
}

@ggj0418 ggj0418 closed this as completed Jul 8, 2024
Copy link

github-actions bot commented Jul 8, 2024

This issue is now closed. Comments on closed issues are hard for our team to see.
If you need more assistance, please open a new issue that references this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
pending-triage question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant