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

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

  const message = useInput("");

  let messageObj, roomNum, messageText, messageTime, newMsgObj, messageArray;

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

  const { data: messageList } = useQuery(SEE_ALL_MESSAGE, {
    variables: { roomId: roomNum },
  });
  if (messageList !== undefined) {
    messageList.seeAllMessage.map((e) => {
      if (e.sender.avatarUrl === "") {
      }
    });
    messageArray = messageList;
  }

  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");
        } else {
          const {
            data: {
              createMessage: { text, createdAt },
            },
          } = messageObj;
          messageText = text;
          messageTime = createdAt;
          newMsgObj = messageObj;
        }
      } catch {
        toast.error("text must be not empty");
      }
    }
  };
  return (
    <ChatPresenter
      location={location}
      message={message}
      onSubmit={onSubmit}
      messageText={messageText}
      messageTime={messageTime}
      newMsgObj={newMsgObj}
      messageArray={messageArray}
    />
  );
});