-
class Fetcher {
private instance: AxiosInstance;
constructor() {
this.instance = axios.create({
baseURL: process.env.NEXT_PUBLIC_BASE_URL,
timeout: 5 * 1000,
withCredentials: true,
});
}
public async doFetch<T>(config: AxiosRequestConfig): Promise<T> {
const { data } = await this.instance<T>({
...config,
});
return data;
}
} abstract class Mutation extends Fetcher {
mutationFn<T>(url: string, method: "post" | "put" | "patch" | "delete", data?: any) {
return this.doFetch<T>({
method,
url,
data,
});
}
mutationOptions = <TData = unknown, TError = Error, TVariables = void, TContext = unknown>(
options: UseMutationOptions<TData, TError, TVariables, TContext>,
): UseMutationOptions<TData, TError, TVariables, TContext> => options;
} class AuthMutation extends Mutation {
private queryClient = useQueryClient();
private router = useRouter()
changePassword() {
return this.mutationOptions({
mutationFn: (password) => this.mutationFn<ChangePasswordMutation>("/auth/password", "post", password),
onSuccess: () => {
toast.success("비밀번호가 변경되었습니다.");
this.queryClient.invalidateQueries({ queryKey: ["user"] });
this.router.push("/signin")
},
onError: (error) => {
toast.error("비밀번호 변경에 실패했습니다.");
},
});
}
} export default function Page() {
const { mutate } = useMutation(new AuthMutation().changePassword())
return ()
} This code is an excerpt from my small project. According to React Hook rules, useQueryClient or useMutation should be called inside a component or another hook, but strangely, calling useQueryClient or useMutation inside a class works without any issues. Has anyone experienced this behavior before, or do you know why this happens? Also, I use mutationOptions in this way for type safety, but I’m curious why React Query doesn't officially support this pattern. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
you are violating the rules-of-hooks, but it will work as long as the class is only called within a React component, and if its not called conditionally. Try creating a |
Beta Was this translation helpful? Give feedback.
you are violating the rules-of-hooks, but it will work as long as the class is only called within a React component, and if its not called conditionally. Try creating a
new AuthMutation()
in a button click handler and you will see it fail.