Skip to content

Instantly share code, notes, and snippets.

@sdanko
Last active November 26, 2021 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdanko/e718365be6ecb5f3f7924de2ca25ab34 to your computer and use it in GitHub Desktop.
Save sdanko/e718365be6ecb5f3f7924de2ca25ab34 to your computer and use it in GitHub Desktop.
React Apollo: Using Subscriptions
const Chat = ({user}) => {
const [addMessage] = useMutation(addMessageMutation);
const { data } = useQuery(messagesQuery);
const messages = data ? data.messages : [];
useSubscription(messageAddedSubscription, {
onSubscriptionData: ({client, subscriptionData}) => {
client.writeQuery({
query: messagesQuery,
data: {
messages: [...messages, subscriptionData.data.messageAdded]
}
});
}
});
return (
<section className="section">
<div className="container">
<h1 className="title">Chatting as {user}</h1>
<MessageList user={user} messages={messages}/>
<MessageInput onSend={addMessage}/>
</div>
</section>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment