Skip to content

Instantly share code, notes, and snippets.

@sdanko
Last active November 26, 2021 13:25
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/e5cc65148ceb077a6e0c32c349f24a3b to your computer and use it in GitHub Desktop.
Save sdanko/e5cc65148ceb077a6e0c32c349f24a3b to your computer and use it in GitHub Desktop.
React Apollo: Using Subscriptions
const Chat = ({user}) => {
const [addMessage] = useMutation(addMessageMutation);
const { data, subscribeToMore } = useQuery(messagesQuery);
const messages = data ? data.messages : [];
useEffect(() => {
subscribeToMore({
document: messageAddedSubscription,
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
const newChat = subscriptionData.data.messageAdded;
return {
messages: [...prev.messages, newChat],
};
},
});
}, []);
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