Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.4 kB
3
Indexable
Never
import { Fragment} from "react";
import classes from "./UserProfile.module.css";
import { useSession } from "next-auth/react";
import { dbs } from "../../utils/firebase";
import { useCollection } from "react-firebase-hooks/firestore";
import { useRouter } from "next/dist/client/router";

const UserProfile = (props) => {
  const router = useRouter();
  const { data: session } = useSession();
  const { image, name, email, bio, currentEmail, message, userScores } = props;
  const currentUser = email === session?.user.email;

  const userChatRef = dbs
    .collection("chats")
    .where("users", "array-contains", currentEmail);
  const [chatSnapshot] = useCollection(userChatRef);
  const chatAlreadyExists = (email) =>
    !!chatSnapshot?.docs.find(
      (chat) => chat.data().users.find((user) => user === email)?.length > 0
    );
  const createChat = () => {
    if (session) {
      if (!chatAlreadyExists(email)) {
        dbs.collection("chats").add({
          users: [currentEmail, email],
        });
      }
      router.push(`/chat/${email}`);
    }
  };
  return (
    <Fragment>
      <div className={classes.wrapper}>
          <div className={classes.about}
            {currentUser && <Button link="/user/edit"> EDIT </Button>}
            {!currentUser && <Button onClick={createChat}> message </Button>}
          </div>
        </div>
    </Fragment>
  );
};

export default UserProfile;