TwitchClone / src / utils / helpers / handleFollow / index.tsx
index.tsx
Raw
import type { Dispatch, SetStateAction } from "react";
import type { UserSchema } from "../../../types/user";
import type { Session } from "next-auth";
import type { UserFollows } from "@prisma/client";
import { api } from "../../api";
import type { RoomDataSchema } from "../../../types/roomData";
import { v4 } from "uuid";
// import { determineFollowing } from "../determineFollowing";
// import { useRoomDataContext } from "../../context/RoomDataContext";
// import { TRPCClientErrorLike } from "@trpc/client";
// import { User } from "@prisma/client";
// import { BuildProcedure, RootConfig, unsetMarker } from "@trpc/server";
// import { UseTRPCMutationResult } from "@trpc/react-query/dist/shared/hooks/types";

type Props = {
  userProfile_: UserSchema;
  // setLocalUserData: Dispatch<any>;
  setLocalUserData: Dispatch<SetStateAction<UserSchema>>;

  // setUserProfile_: Dispatch<any>;
  user: Session | null;
  // setUser: React.Dispatch<React.SetStateAction<UserSchema | null>>;
  followId: string;
  roomData: RoomDataSchema;
  updateFollowingMutation: ReturnType<
    typeof api.lambda.updateFollowing.useMutation
  >;
  updateLocalData: (newData: UserSchema) => void;

  // updateFollowingMutation: UseTRPCMutationResult<
  //   User & { following: UserFollows[] } | null,
  //   TRPCClientErrorLike<BuildProcedure<
  //     'mutation',
  //     {
  //       _config: RootConfig;
  //       _output_out: typeof unsetMarker;
  //     },
  //     User & { following: UserFollows[] } | null
  //   >>
  // >['mutate'];
};
export const handleFollow = (e: React.MouseEvent, props: Props) => {
  const {
    userProfile_,
    // setUserProfile_,
    setLocalUserData,
    user,
    followId,
    roomData,
    updateFollowingMutation,
    updateLocalData,
  } = props;
  // const { roomData, setRoomData, userData, setUserData } = useRoomDataContext();
  // let updateFollowingMutation = api.lambda.updateFollowing.useMutation();
  console.log("props", props);
  // e.preventDefault();
  type InitUserDbData = {
    following: UserFollows[];
  };

  const initUserDbData = roomData?.userData as { following: UserFollows[] };

  // const initUserDbData: InitUserDbData = roomData.userData;
  // const differences = determineFollowing(
  //   userProfile_,
  //   roomData?.userData.following
  // );
  console.log("init", initUserDbData);
  const action =
    userProfile_ && userProfile_.following?.length === 0 && initUserDbData
      ? "add"
      : initUserDbData?.following?.some(
          (follow: UserFollows) => follow.followingId === followId
        )
      ? // : initUserDbData?.following?.some(
        //     (follow: any) =>
        //       differences.length > 0 && follow.id === differences[0]?.id
        //   )
        "remove"
      : "add";
  console.log("differences", action);
  let updatedFollowing: UserFollows[] = [];
  // if (
  //   differences.length > 0 ||
  //   (userProfile_ && userProfile_.following?.length === 0)
  // )

  if (action === "add" && user) {
    updatedFollowing = [
      ...(userProfile_.following ?? []),
      {
        id: v4(),
        followerId: user.user?.id as string,
        followingId: followId,
        createdAt: new Date(),
      },
    ];
    console.log(updatedFollowing.map((follow) => typeof follow.createdAt));
  } else if (action === "remove") {
    // updatedFollowing = (userProfile_.following || []).filter(
    //   (follow: any) => follow.followingId == followId
    // );
    console.log(
      initUserDbData.following.map((follow) => typeof follow.createdAt)
    );
    updatedFollowing = initUserDbData?.following?.filter(
      (follow: UserFollows | null) => follow && follow.followingId === followId
    );
    console.log(updatedFollowing.map((follow) => typeof follow.createdAt));
  }

  if (
    (action === "add" &&
      !initUserDbData.following.some(
        (follow: UserFollows) => follow.followingId === followId
      )) ||
    (action === "remove" &&
      initUserDbData.following.some(
        (follow: UserFollows) => follow.followingId === followId
      ))
  ) {
    console.log("action/dif", action, "arr", []);
    console.log("updatedFollowing", updatedFollowing);
    updatedFollowing = updatedFollowing.map((follow) => ({
      ...follow,
      createdAt: new Date(follow.createdAt),
    }));

    console.log(updatedFollowing.map((follow) => typeof follow.createdAt));
    updateFollowingMutation.mutate(
      {
        // following:
        //   differences.length > 0
        //     ? differences
        //     : userProfile_?.following?.length == 0
        //     ? []
        //     : userProfile_?.following || [],
        following: updatedFollowing,
        userId: user?.user?.id || "",
        email: user?.user?.email || "",
        action: action,
      },
      {
        onSuccess: (data) => {
          console.log("data", data);
          setLocalUserData((prev: UserSchema) => {
            console.log("prev", prev);
            return {
              ...prev,
              following: data?.following || [],
            };
          });
          updateLocalData({
            ...userProfile_,
            following: data?.following || [],
          });
        },

        // onSuccess: (data) => {
        //   console.log("data", data);
        //   // console.log('local', localUserData)
        //   setLocalUserData((prev: UserFollows) => {
        //     console.log("prev", prev);
        //     return {
        //       ...data,
        //     };
        //   });
        //   updateLocalData({
        //     ...userProfile_,
        //     following: data?.following || [],
        //   });
        //   // setUserProfile_({
        //   //   ...userProfile_,
        //   //   following: data?.following || [],
        //   // });
        // },
        onError: (error) => {
          console.log("error", error);
        },
      }
    );
  }
};