DoneDeal0
DoneDeal0

Reputation: 6257

React query useMutation error: onLogout is not a function

I'm implementing React Query's useMutation for a simple api call (a user logout). I've written a code that seems correct, but when triggering the mutation, React claims that onLogout is not a function. How to fix this?

Here is the code:

// the api service
const _logout =()=> {
 return api.post("/logout")
  .then(res=> res)
  .catch(err=> err)
}

const logout: AuthService["logout"] = async () => {
  const { mutateAsync } = useMutation(() => _logout(), {
    onSuccess: () => deleteUser()
  })
  const onLogout = () => mutateAsync();
  return {
    onLogout,
  }
};

// the typescript interface
  export interface AuthService {
    logout: () => { onLogout: () => Promise<any> };
  }

// the function into action
function MyComponent(){
  const { onLogout } = useService("auth").logout();
  return (
  <button onClick={onLogout}>logout</button>
  )
  }

Also, typescript claims that:

Type '() => Promise<{ onLogout: () => Promise; }>' is not assignable to type '() => { onLogout: () => Promise; }'.

But I want to only return an object with a onLogout function, and maybe later a loading state, ect. Not a promise.

Thanks for your help!

Upvotes: 0

Views: 3414

Answers (1)

Oro
Oro

Reputation: 2586

Async function always returns Promise

You are using async keyword and don't use any await inside your logout function.

Upvotes: 4

Related Questions