Amplify UI React v6 fetchAuthSession returns undefined values

151 Views Asked by At

I am trying AWS Amplify UI Authenticator for React v6, I tried fetchAuthSession to get user session after successful login but it returns undefined values. Is there additional configurations that needs to be done?

 import React, { useState, useEffect } from "react";
import { Authenticator, useAuthenticator } from "@aws-amplify/ui-react";
import { fetchAuthSession } from "aws-amplify/auth";

const App = () => {
    const { user, signOut } = useAuthenticator((context) => [context.user]);


    Amplify.configure({
      Auth: {
        Cognito: {
          userPoolClientId: <client id>,
          userPoolId: <user pool id>,
        },
      },
    });

    useEffect(() => {
      if (user?.username) {
        printAccessTokenAndIdToken(); 
      }
    }, [user]);  

    const printAccessTokenAndIdToken = async () => {
      try {
        const session = await fetchAuthSession(); // Fetch the authentication session
        console.log("Access Token:", session?.tokens?.accessToken.toString()); 
        console.log("ID Token:", session?.tokens?.idToken?.toString());
      } catch (e) {
        console.log(e);
      }
    };

    return  (
      <Authenticator
        hideSignUp={true}
        components={components}
        loginMechanisms={["username"]}
      >
        {({signOut}) => {
          <button onClick={signOut}></button>
        }}
      </Authenticator>
     );

}
0

There are 0 best solutions below