Aws Amplify: Onstatuschange Then Render Main Page
Solution 1:
If you resolved it I hope it will help someone else.
I think the following is a better option than using 'onAuthStateChange':
from Amplify dox :
import { Auth } from'aws-amplify';
Auth.currentAuthenticatedUser({
bypassCache: false// Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
}).then(user =>console.log(user))
.catch(err =>console.log(err));
You can add your logic within '.then(user => ...' to add route to your protected pages. Also you can redirect to Login page from '.catch(err => '.
If you include above code within a function and call it from 'componentWillReceiveProps' it should be called every time auth status changes.
Solution 2:
This is really about rendering and state (and not anything to do with AWS Amplify). First, set up state in your constructor:
constructor(props) {
super(props);
this.state = { authState: '' };
}
Then, your onAuthStateChange()
becomes:
onAuthStateChange(newState) {
if (newState === 'signedIn') {
this.setState({ authState: newState });
}
}
Finally, in your render()
method, you adjust your rendering so that it does "the right thing" based on your auth state.
render() {
if (this.state.authState === 'signedIn') {
return (<ApolloProvider ...><MyApp/></ApolloProvider>);
} else {
return (<Authenticator .../>);
}
}
You can abstract this away with a HOC as well (the same way the withAuthenticator()
HOC from AWS Amplify does it). Basically, the Authenticator gets displayed initially. Once the signedIn state is received, the internal component state is updated and that causes a re-render of the component with the rest of your app.
Post a Comment for "Aws Amplify: Onstatuschange Then Render Main Page"