T
TanStack3y ago
other-emerald

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

I have this function that mutate posts
export const useMutatePost = (type: "create" | "update" | "delete") => {
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)
);
},
});
}
};
export const useMutatePost = (type: "create" | "update" | "delete") => {
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'.
3 Replies
adverse-sapphire
adverse-sapphire3y ago
This would need overloads or conditional return types. Why not make two custom hooks?
wise-white
wise-white3y ago
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?
other-emerald
other-emeraldOP3y ago
I wasn't sure if this was a bad practice. I was just trying to make the code more concise I'll split it, thanks guyts

Did you find this page helpful?