Newer
Older
taehui / taehui-fe / src / query / usePutAvatar.ts
@Taehui Taehui on 17 Mar 1 KB 2024-03-17 오후 3:50
import { useTaehuiStore } from "@/state/Stores";
import { isClientFault, wwwAPI } from "@/utilities/wwwAPI";
import { useMutation } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { toast } from "react-toastify";
import Swal from "sweetalert2";
import { getMillis } from "taehui-ts/date";
import { useTo } from "taehui-ts/fe-utilities";

export default function usePutAvatar() {
  const t = useTranslations();

  const { totem, setSession, saveTotem } = useTaehuiStore();

  const to = useTo();

  return useMutation({
    mutationFn: async ({
      avatarCipher,
      avatarCipherModified,
      avatarName,
      fax,
      avatarIntro,
    }: {
      avatarCipher: string;
      avatarCipherModified: string;
      avatarName: string;
      fax: string;
      avatarIntro: string;
    }) => {
      const { data } = await wwwAPI.put(
        "/avatar",
        {
          avatarCipher,
          avatarCipherModified,
          avatarName,
          fax,
          avatarIntro,
        },
        {
          headers: {
            millis: getMillis(),
            totem,
          },
        },
      );
      return data;
    },
    onSuccess: async (data, { avatarName, fax, avatarIntro }) => {
      if (data) {
        setSession({
          totem: "",
          avatarID: "",
          avatarName: "'",
          level: 0,
          fax: "",
          avatarIntro: "",
        });
        saveTotem();
        await Swal.fire(t("doModifyAvatar"), t("doModifiedAvatar"), "success");
      } else {
        setSession({
          avatarName,
          fax,
          avatarIntro,
        });
        saveTotem();
        to("/");
      }
    },
    onError: (e) => {
      if (isClientFault(e)) {
        toast.error(t("failedValidateCipher"));
      }
    },
  });
}