У меня есть проблема, когда я перенаправляю обратно с экрана входа в Cognito, мое состояние не меняется на true для Auth Users.Магазин authStore начинает работать только тогда, когда я сильно обновляю страницу.если я использую React Routes, я не могу изменить состояние, даже если оно не обновляет authStore.
Мой файл конфигурации хранилища аутентификации
import Amplify, { Auth, Hub } from 'aws-amplify';
import { awsConfig, signInUrl } from './auth-config';
class AuthStore {
constructor(history) {
this.history = history;
console.log(this.history);
this.registerHubListener();
Amplify.configure(awsConfig);
}
subscribe = subscriber => {
this.subscriber = subscriber;
};
unsubscribe = () => {
this.subscriber = null;
};
notify = authenticated => {
if (this.subscriber) this.subscriber(authenticated);
};
isAuthenticated = () => {
return Boolean(Auth.userPool.getCurrentUser());
};
getCredentials = async () => {
try {
const credentials = await Auth.currentCredentials();
this.notify(credentials.authenticated);
return credentials;
} catch (err) {
this.notify(false);
}
};
registerHubListener = () => {
const self = this;
const hubListener = {
onHubCapsule: async capsule => {
if (capsule.payload.event === 'configured') {
self.notify(self.isAuthenticated());
}
if (capsule.payload.event === 'cognitoHostedUI') {
self.notify(self.isAuthenticated());
console.log('self.isAuthenticated()', self.isAuthenticated());
self.history.push('/');
}
},
};
Hub.listen('auth', hubListener.onHubCapsule);
};
signIn = () => {
window.location.assign(signInUrl);
};
signOut = async () => {
try {
await Auth.signOut();
} catch (err) {
console.error(err);
}
};
}
export default AuthStore;
, и вот мой простой React Component, гдеУ меня проблема с
// @flow
import * as React from 'react';
type Props = {
authStore: Object
}
type State = {
authUser: boolean
}
class Component extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
authUser: this.props.authStore.isAuthenticated(),
};
}
componentDidMount() {
this.props.authStore.subscribe(this.handleAuthChange);
}
componentWillUnmount() {
this.props.authStore.unsubscribe();
}
handleAuthChange = (authenticated) => {
this.setState({ authUser: authenticated });
};
render() {
const { authStore } = this.props;
const { authUser } = this.state;
return (
<div className={styles.headerMenu}>
{console.log(authUser)}
{authUser && (
<button
onClick={authStore.signOut}
className={styles.headerUser}
>
log out
</button>
)}
{!authUser && (
<button
onClick={authStore.signIn}
className={styles.headerUser}
>
login
</button>
)}
</div>
);
}
}
export default Component;