我使用下面的钩子通过 AWS Cognito 进行身份验证。当用户登录时,它不会运行,因此 React 认为用户仍未通过身份验证。如果我刷新页面,一切正常。我做错了什么?
import { useState, useEffect, useMemo } from "react";
import { Auth } from "aws-amplify";
interface User {
email: string;
id: string;
isAuthenticated: boolean;
loading: boolean;
}
const useAuth = () => {
const [user, setUser] = useState<User>({
email: "",
id: "",
isAuthenticated: false,
loading: true,
});
const auth = useMemo(() => {
Auth.configure({
userPoolId: process.env.REACT_APP_COGNITO_USER_POOL_ID,
userPoolWebClientId: process.env.REACT_APP_COGNITO_APP_CLIENT_ID,
});
return Auth;
}, []);
useEffect(() => {
const checkUser = async () => {
try {
const user = await auth.currentAuthenticatedUser();
setUser({
email: user.attributes.email,
id: user.attributes.sub,
isAuthenticated: true,
loading: false,
});
return null;
} catch (e) {
setUser({
email: "",
id: "",
isAuthenticated: false,
loading: false,
});
return null;
}
};
checkUser();
}, []);
return user;
};
export default useAuth;