T
TanStack3y ago
continuing-cyan

React query mutations

Hi guys I wrote this custom function in react-query to simplify my code
import { useMutation, useQuery } from '@tanstack/react-query';

import userRequest from '@/utils/AxiosInstance';




export const usePostQuery = <TResponse, TBody>(

queryKey: string,

url: string,

body: TBody

) => {

return useMutation({

mutationKey: [queryKey],

mutationFn: async () => {

const { data } = await userRequest.post(url, body);

return data as TResponse;

},

onSuccess: (data: TResponse) => {

console.log(data);

},

onError: (err) => {

console.error(err);

},

});

};
import { useMutation, useQuery } from '@tanstack/react-query';

import userRequest from '@/utils/AxiosInstance';




export const usePostQuery = <TResponse, TBody>(

queryKey: string,

url: string,

body: TBody

) => {

return useMutation({

mutationKey: [queryKey],

mutationFn: async () => {

const { data } = await userRequest.post(url, body);

return data as TResponse;

},

onSuccess: (data: TResponse) => {

console.log(data);

},

onError: (err) => {

console.error(err);

},

});

};
but when i try to call it inside onsubmit in formik
onSubmit={(values) => {

const data = usePostQuery();

}}
onSubmit={(values) => {

const data = usePostQuery();

}}
It throws this error
React Hook "usePostQuery" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function.eslintreact-hooks/rules-of-hooks

Expected 3 arguments, but got 0.ts(2554)

postQuery.ts(5, 3): An argument for 'queryKey' was not provided.

(alias) usePostQuery<unknown, unknown>(queryKey: string, url: string, body: unknown): UseMutationResult<unknown, unknown, void, unknown>
import usePostQuery
React Hook "usePostQuery" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function.eslintreact-hooks/rules-of-hooks

Expected 3 arguments, but got 0.ts(2554)

postQuery.ts(5, 3): An argument for 'queryKey' was not provided.

(alias) usePostQuery<unknown, unknown>(queryKey: string, url: string, body: unknown): UseMutationResult<unknown, unknown, void, unknown>
import usePostQuery
can you guys correct me if I write this fuction wrong, Thank you
1 Reply
sunny-green
sunny-green3y ago
have a look at our mutation examples. you call useMutation at the top of your component, then invoke the returned .mutate function in the onSubmit handler. you cannot call hooks conditionally, that's a rule of react

Did you find this page helpful?