React query useMutation error: onLogout is not a function
React query useMutation error: onLogout is not a function
我正在为一个简单的 api 调用(用户注销)实现 React Query 的 useMutation。我写了一个看起来正确的代码,但是当触发突变时,React 声称 onLogout is not a function
。如何解决这个问题?
代码如下:
// 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>
)
}
此外,打字稿声称:
Type '() => Promise<{ onLogout: () => Promise; }>' is not assignable to type '() => { onLogout: () => Promise; }'.
但我只想 return 一个具有 onLogout
函数的对象,也许稍后还有一个 loading
状态,等等。不是承诺。
感谢您的帮助!
异步函数始终returnsPromise
您正在使用 async
关键字并且不要在注销函数中使用任何 await
。
我正在为一个简单的 api 调用(用户注销)实现 React Query 的 useMutation。我写了一个看起来正确的代码,但是当触发突变时,React 声称 onLogout is not a function
。如何解决这个问题?
代码如下:
// 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>
)
}
此外,打字稿声称:
Type '() => Promise<{ onLogout: () => Promise; }>' is not assignable to type '() => { onLogout: () => Promise; }'.
但我只想 return 一个具有 onLogout
函数的对象,也许稍后还有一个 loading
状态,等等。不是承诺。
感谢您的帮助!
异步函数始终returnsPromise
您正在使用 async
关键字并且不要在注销函数中使用任何 await
。