😸

【Drizzle ORM】NextJs14 と Drizzle ORM【#32 Profile Update Hook】

2024/11/20に公開

【#32 Profile Update Hook】

YouTube: https://youtu.be/HKDrRfuT4U0
https://youtu.be/HKDrRfuT4U0

今回はプロフィールのアップデート用のhooksを作成していきます。

hooks/profiles/use-update-profiles.ts
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { InferRequestType, InferResponseType } from "hono";

import { client } from "@/lib/hono";

type ResponseType = InferResponseType<
  (typeof client.api.profiles)[":id"]["$patch"]
>;
type RequestType = InferRequestType<
  (typeof client.api.profiles)[":id"]["$patch"]
>["json"];

export const useUpdateProfile = () => {
  const queryClient = useQueryClient();

  const mutation = useMutation<ResponseType, Error, RequestType>({
    mutationFn: async (json) => {
      const { id } = json;
      const response = await client.api.profiles[":id"]["$patch"]({
        json,
        param: { id },
      });

      if (!response.ok) {
        throw new Error("Failed to update profile");
      }

      return await response.json();
    },
    onSuccess: () => {
      toast.success("Profile updated");
      queryClient.invalidateQueries({ queryKey: ["clerk-user"] });
    },
    onError: () => {
      toast.error("Failed to update profile");
    },
  });

  return mutation;
};

Discussion