Newer
Older
taehui / taehui-fe / src / avatar / usePutAvatar.ts
@Taehui Taehui on 13 Mar 1 KB v1.0.0
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import Swal from "sweetalert2";
import { toast } from "react-toastify";
import { getMillis } from "taehui-ts/date";
import { useTo } from "taehui-ts/fe-utility";

import { isClientFault, wwwAXIOS } from "src/Www";
import { useAvatarStore } from "src/Stores";
import { isAxiosError } from "axios";

export default function usePutAvatar() {
  const { t } = useTranslation();

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

  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 wwwAXIOS.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"));
      }
    },
  });
}