Skip to content

Instantly share code, notes, and snippets.

@ramsaylanier
Created May 13, 2020 23:57
Show Gist options
  • Save ramsaylanier/324e3c5a85bf3306430f3291e6c03297 to your computer and use it in GitHub Desktop.
Save ramsaylanier/324e3c5a85bf3306430f3291e6c03297 to your computer and use it in GitHub Desktop.
Using Pusher instead of the GraphQL subscription spec
const PageList = () => {
const [value, setValue] = React.useState('')
usePusher('pageAdded', ({ client, data }) => {
// client is an instance of ApolloClient
let { pages } = client.readQuery({ query, variables })
pages = [data, ...pages]
client.writeQuery({ query, variables, data: { pages } })
})
....
}
...
createPage: async (parent, args, { db, pusher }) => {
const collection = db.collection('Pages')
try {
const newPage = await collection.save({
title: args.title,
lastEdited: new Date(),
})
const document = await collection.document(newPage)
// TRIGGER
pusher.trigger('subscription', 'pageAdded', {
message: { ...document, __typename: 'Page' },
})
return document
} catch (e) {
console.log(e)
}
},
...
import React from 'react'
import Pusher from 'pusher-js'
import { useApolloClient } from '@apollo/react-hooks'
var pusher = new Pusher('YourPusherKeyHere', {
cluster: 'us2',
})
var channel = pusher.subscribe('subscription')
const usePusher = (messageType, callback) => {
const client = useApolloClient()
React.useEffect(() => {
channel.bind(
messageType,
function ({ message }) {
callback({ client, data: message })
},
[messageType]
)
return () => channel.unbind(messageType)
}, [])
}
export default usePusher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment