Created
May 13, 2020 23:57
-
-
Save ramsaylanier/324e3c5a85bf3306430f3291e6c03297 to your computer and use it in GitHub Desktop.
Using Pusher instead of the GraphQL subscription spec
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
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 } }) | |
}) | |
.... | |
} |
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
... | |
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) | |
} | |
}, | |
... |
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 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