Home > other >  How do I type onSuccess data in React Query?
How do I type onSuccess data in React Query?

Time:11-12

I have API call function (httpClient is axios instance)


interface IRegisterResponse {
  accessToken: string;
}

export const register = async ({
  name,
  password,
  token,
}: IRegisterParams) =>
  await httpClient.post<IRegisterResponse>('register', {
    name,
    password,
    token,
  });

And I have useMutation hook that handles this API call form me

  const { mutate: registerMutation } = useMutation(
    ['register'],
    register,
    {
      onSuccess: ({ accessToken }) => console.log(accessToken),
    }
  );

But in onSuccess callback it highlights accessToken with message Property 'accessToken' does not exist on type 'AxiosResponse<IRegisterResponse, any>'

What am I doing wrong and how should I type it?

CodePudding user response:

You are returning axios response, not data

onSuccess: ({ data: { accessToken } }) => console.log(accessToken)

or

export const register = async ({
  name,
  password,
  token,
}: IRegisterParams) =>
  (await httpClient.post<IRegisterResponse>('register', {
    name,
    password,
    token,
  })).data;
  • Related