ChatContainer.js 1.71 KB
import React from "react";
import { useSubscription, useMutation, useQuery } from "@apollo/react-hooks";
import ChatPresenter from "./ChatPresenter";
import { withRouter } from "react-router-dom";
import {
  SUBSCRIPTION_MSG,
  WHOLE_MESSAGE,
  GET_ROOM_BY_NAME,
} 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);

  let messageObj, outcomingMsg, outcomingTime, roomNum;

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

  const [createMsg] = useMutation(WHOLE_MESSAGE);
  //const { data } = useSubscription(SUBSCRIPTION_MSG);

  const message = useInput("");

  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 { text, createdAt } = messageObj;
          outcomingMsg = text;
          outcomingTime = createdAt;
        }
      } catch {
        toast.error("text must be not empty");
      }
    }
  };
  return (
    <ChatPresenter
      location={location}
      message={message}
      onSubmit={onSubmit}
      outcomingMsg={outcomingMsg}
      outcomingTime={outcomingTime}
    />
  );
});