sdy

update subscription

import React from "react";
import React, { useEffect, useState } from "react";
import { useMutation, useQuery } from "@apollo/react-hooks";
import ChatPresenter from "./ChatPresenter";
import { withRouter } from "react-router-dom";
......@@ -12,6 +12,7 @@ import useInput from "../../Hooks/useInput";
import { toast } from "react-toastify";
export default withRouter(({ location }) => {
const [messageArr, setMessageArr] = useState([]);
const { pathname } = location;
const roomName = pathname.slice(1, pathname.length);
const [createMsg] = useMutation(CREATE_MESSAGE);
......@@ -30,7 +31,12 @@ export default withRouter(({ location }) => {
roomNum = Number(roomId);
}
const { subscribeToMore, data: messageList } = useQuery(SEE_ALL_MESSAGE, {
const {
subscribeToMore,
data: messageList,
error: msgQueryError,
loading: msgQueryyLoading,
} = useQuery(SEE_ALL_MESSAGE, {
variables: { roomId: roomNum },
});
......@@ -43,12 +49,27 @@ export default withRouter(({ location }) => {
messageArray = messageList;
}
let resultObj = subscribeToMore({
document: SUBSCRIPTION_MSG,
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
},
});
useEffect(() => {
if (msgQueryError) {
console.error(msgQueryError);
}
if (messageArr) {
setMessageArr(messageArr.seeAllMessage);
}
}, [msgQueryyLoading]);
const subscribeToNewMessage = () => {
subscribeToMore({
document: SUBSCRIPTION_MSG,
updateQuery: (currentMessages, { subscriptionData }) => {
if (!subscriptionData.data) return currentMessages;
const newMessage = subscriptionData.data.subMessage;
const updateMessages = currentMessages.seeAllMessage.concat(newMessage);
setMessageArr(updateMessages);
return { seeAllMessage: updateMessages };
},
});
};
const onSubmit = async (e) => {
e.preventDefault();
......@@ -75,6 +96,7 @@ export default withRouter(({ location }) => {
message={message}
onSubmit={onSubmit}
messageArray={messageArray}
subscribeToNewMessage={subscribeToNewMessage}
/>
);
});
......