ChatContainer.js 2.42 KB
import React, { useEffect } from "react";
import { useMutation, useQuery, useSubscription } from "@apollo/react-hooks";
import ChatPresenter from "./ChatPresenter";
import { withRouter } from "react-router-dom";
import {
  CREATE_MESSAGE,
  GET_ROOM_BY_NAME,
  SEE_ALL_MESSAGE,
  SUBSCRIPTION_MSG,
} from "./ChatQueries";
import useInput from "../../Hooks/useInput";
import { toast } from "react-toastify";

export default withRouter(({ location }) => {
  const { pathname } = location;
  const roomName = pathname.slice(1, pathname.length);
  const [createMsg] = useMutation(CREATE_MESSAGE);
  const { data: subScription } = useSubscription(SUBSCRIPTION_MSG);

  const message = useInput("");

  let messageObj, roomNum, messageArray;

  const { data: getRoom } = useQuery(GET_ROOM_BY_NAME, {
    variables: { roomName },
  });
  if (getRoom !== undefined) {
    const {
      getRoomByName: { id: roomId },
    } = getRoom;
    roomNum = Number(roomId);
  }

  const { subscribeToMore, data: messageList } = useQuery(SEE_ALL_MESSAGE, {
    variables: { roomId: roomNum },
  });

  if (messageList !== undefined) {
    messageList.seeAllMessage.map((e) => {
      if (e.sender.avatarUrl === "") {
        e.sender.avatarUrl = "../../imgs/defaultProfile.jpg";
      }
    });
    messageArray = messageList;
  }

  let testObj;
  testObj = subscribeToMore({
    document: SUBSCRIPTION_MSG,
    updateQuery: (prev, { subscriptionData }) => {
      console.log("prev : ", prev);
      console.log("subscriptionData : ", subscriptionData);
      if (!subscriptionData.data) return prev;
      const newFeedItem = subscriptionData.data.subMessage;
      console.log("newFeedItem : ", newFeedItem);
      return Object.assign({}, prev, {
        seeAllMessage: {
          id,
        },
      });
    },
  });
  console.log(testObj);

  const onSubmit = async (e) => {
    e.preventDefault();
    if (message.value !== undefined || message.value !== "") {
      try {
        messageObj = await createMsg({
          variables: {
            message: message.value,
            roomId: roomNum,
          },
        });
        if (!messageObj) {
          toast.error("fail to create new message !, try again");
        }
      } catch {
        toast.error("text must be not empty");
      }
    }
  };

  useEffect(() => {});

  return (
    <ChatPresenter
      location={location}
      message={message}
      onSubmit={onSubmit}
      messageArray={messageArray}
    />
  );
});