AuthContainer.js 2.85 KB
import React, { useState } from "react";
import { useMutation } from "@apollo/react-hooks";
import { LOGIN, SIGNUP } from "./AuthQueries";
import useInput from "../../Hooks/useInput";
import { toast } from "react-toastify";
import AuthPresenter from "./AuthPresenter";

export default () => {
  const [action, setAction] = useState("logIn");

  const email = useInput("");
  const password = useInput("");
  const password2 = useInput("");
  const phoneNum = useInput("");
  const username = useInput("");

  // mutations
  const loginMutation = useMutation(LOGIN, {
    variables: { email: email.value, password: password.value },
  });

  const createAccountMutation = useMutation(SIGNUP, {
    variables: {
      email: email.value,
      username: username.value,
      password: password.value,
      password2: password2.value,
      phoneNum: phoneNum.value,
    },
  });

  // TODO: make login success query.

  const onSubmit = async (e) => {
    if (action === "logIn") {
      if (email.value !== "") {
        try {
          // QL 을 통해서 data 를 가져온다.
          const {
            data: { login }, // AuthQueries 에 정의된 mutation 값
          } = await loginMutation();
          if (!login) {
            toast.warn("you need to make your own account");
            setAction("signUp");
          } else {
            toast.success("login success");
            setAction("confirm");
          }
        } catch (e) {}
      } else {
        // TODO: inform "email is required" using toastify
        toast.error("email is required!", {
          position: "top-center",
          autoClose: 3000,
          closeOnClick: true,
          draggable: true,
        });
      }
    } else if (action === "signUp") {
      if (
        (email.value !== "",
        username.value !== "",
        password.value !== "",
        password2.value !== "",
        phoneNum.value !== "")
      ) {
        try {
          const {
            data: { signUp },
          } = await createAccountMutation();
          if (!signUp) {
            toast.warn("you need to sign up first");
            setAction("signUp");
          } else {
            toast.success("login success");
            setAction("logIn");
          }
        } catch (e) {
          // TODO: can't find data: signUp
          toast.error("can't sign up, please check input data");
        }
      } else {
        // TODO: inform user need to input values that required for sign up with toastify
        toast.error("you need to input with vaild data");
      }
    } else if (action === "confirm") {
      // TODO: when login success, go to Main Container
    }
  };

  return (
    <AuthPresenter
      setAction={setAction}
      action={action}
      email={email}
      password={password}
      password2={password2}
      username={username}
      phoneNum={phoneNum}
      onSubmit={onSubmit}
    />
  );
};