Skip to content

Instantly share code, notes, and snippets.

@cctoni
Forked from dabit3/SubscriptionHook.js
Created June 10, 2019 12:24
Show Gist options
  • Select an option

  • Save cctoni/56d658604fba64f28e638585bc7424ea to your computer and use it in GitHub Desktop.

Select an option

Save cctoni/56d658604fba64f28e638585bc7424ea to your computer and use it in GitHub Desktop.
Example of using custom React hooks for managing GraphQL subscriptions
import { useEffect, useState } from 'react'
import { API, graphqlOperation } from 'aws-amplify'
const ListTalks = `
query {
listTalks {
items {
name
description
presenter {
name
bio
}
}
}
}
`
const OnCreateTalk = `
subscription {
onCreateTalk {
id
name
description
presenter {
name
bio
}
}
}
`
export default () => {
const [talks, updateTalks] = useState([])
useEffect(async() => {
const talkData = await API.graphql(graphqlOperation(ListTalks))
updateTalks(talkData.data.listTalks.items)
}, [])
useEffect(() => {
const subscription = API.graphql(
graphqlOperation(OnCreateTalk)
).subscribe({
next: data => {
const { value: { data: { onCreateTalk } }} = data
const talkData = [...talks, onCreateTalk]
updateTalks(talkData)
}
})
return () => subscription.unsubscribe()
}, [talks])
return talks
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment