Last active
November 26, 2021 13:25
-
-
Save sdanko/e5cc65148ceb077a6e0c32c349f24a3b to your computer and use it in GitHub Desktop.
React Apollo: Using Subscriptions
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 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