Search code examples
reactjsaws-amplifyamplifyjs

AWS Amplify - How to render components after sign in


I have an AWS Amplify app using React. I want to be able to only load (or reload) a TaskList component only when the user has successfully signed in. However, the component gets rendered from the very beginning when page loads and when user fills up form and gets signed up it won't reload. I have been trying multiple workarounds but I can't see how to make my component depend on a successful login. I rely on the default Amplify authenticator functions to sign the user in against Cognito.

const App = () => (
  <AmplifyAuthenticator>
    <div>
      My App
      <AmplifySignOut />
      <TaskList />
    </div>
  </AmplifyAuthenticator>
);

Solution

  • I managed to solve it using hints given in this answer AWS Amplify: onStatusChange then render main page.

    Basically, I changed my App component to return only sign in form or the whole up based on auth state change.

    const App = () => {
        const [authState, setAuthState] = useState('');
    
        function handleAuthStateChange(state) {
            if (state === 'signedin' || state === 'signedout') {
                setAuthState(state);
            }
        }
    
        return (
          <div>
            { authState !== 'signedin' ?
            <AmplifyAuthenticator>
                <AmplifySignIn handleAuthStateChange={handleAuthStateChange} slot="sign-in"></AmplifySignIn>       
            </AmplifyAuthenticator> 
            :
            <div>
               My App
               <AmplifySignOut handleAuthStateChange={handleAuthStateChange} slot="sign-out"/>
               <TaskList />
            </div>
            } 
          </div>  
        );
    }