Last active
January 26, 2021 16:04
-
-
Save dabit3/ee8f489ebc208502ab9351809e96e70d to your computer and use it in GitHub Desktop.
Example of using custom React hooks for managing GraphQL subscriptions
This file contains 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 { 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
I would further recommend leveraging Apollo Client to do much of the "heavy lifting" ;)