-
-
Save cctoni/56d658604fba64f28e638585bc7424ea to your computer and use it in GitHub Desktop.
Example of using custom React hooks for managing GraphQL subscriptions
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 { 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