#How can i assure to typescript the argument type of useMutation ?

4 messages · Page 1 of 1 (latest)

vernal linden
#

I have this function that mutate posts

  const queryClient = useQueryClient();
  switch (type) {
    case "create":
      return useMutation((payload: CreatePost) => createPost(payload), {
        onSuccess: () => {
          queryClient.invalidateQueries(["profiles"]);
          queryClient.invalidateQueries(["user"]);
          queryClient.invalidateQueries(["posts"]);
        },
        onError: () => {
          throw new Error("Erro");
        },
      });

    case "update":
      return useMutation((payload: MutationPayload) => updatePost(payload), {
        onSuccess: (updatedPost: any) => {
          queryClient.setQueryData(["posts"], (prev: any) =>
            prev.map((post: Post) =>
              post.id === updatedPost.id ? updatedPost : post
            )
          );
        },
      });

    case "delete":
      return useMutation((payload: MutationPayload) => deletePost(payload), {
        onSuccess: (deletedPost: Post) => {
          queryClient.setQueryData(["posts"], (prev: any) =>
            prev.filter((post: Post) => post.id != deletedPost.id)
          );
        },
      });
  }
};```

When i call `  const { mutate } = useMutatePost("create");`, i want to assure typescript that the mutate argument will be the type CreatePost.
But typescript is saying that `Argument of type 'CreatePost' is not assignable to parameter of type 'CreatePost & MutationPayload'.`
acoustic trench
#

This would need overloads or conditional return types. Why not make two custom hooks?

slender frost
#

I second TkDodo, split to custom hooks. does react allow the use of hooks this way anyway? isn't it like putting them behind if?

vernal linden
#

I wasn't sure if this was a bad practice. I was just trying to make the code more concise