typescript TS2769 on react-query(useMutation) hook

Viewed 127

I use react-query useMutation hook and pass axios call inside it but typescript is error

What i'm missing ?

If i type my axios function variable with any - all fine. What type i need to assign to LoginRequest to fix this error?

intrefaces:


interface Login{
    username: string,
    password: string,

}

interface Token{
    data:{
      access_token: string,
      refresh_token: string
    }

}

LoginRequest function:

  const LoginRequest = (username: string, password: string)=> axios.post(url,
      {username: username, password: password}
   )

useMutation hook:

  const loginToServer = useMutation<Token, unknown, Login>(LoginRequest, // TS2769 No overload matches this call. (If type LoginRequest as any all works)
    { 
      onSuccess: (newLogin) => {
        localStorage.setItem('accessToken', newLogin.data.access_token)
        localStorage.setItem('refreshToken', newLogin.data.refresh_token)
        navigate('/main')

      },

      onError: (newLogin) => {
        console.log('onError', newLogin);
      },
    },
  );
2 Answers

Need to type data the same type as type of useMutation argument has

  const LoginRequest = (data: Login)=> axios.post(url,data)

Mutations can only take one argument. If you have a function that takes multiple arguments, you need to either wrap it in an object, or split it up:

const LoginRequest = (params: Login)=> axios.post(url, params)

useMutation(LoginRequest)

or:

const LoginRequest = (username: string, password: string)=> axios.post(url,
    {username: username, password: password}
)

useMutation((login: Login) => LoginRequest(login.username, login.password))
Related