Search code examples
reactjsamazon-web-servicesamazon-cognitoaws-amplify

AWS Amplify HOC Authenticator React does not pass authState property to wrapped component


I am trying to use Amplify Authenticator to block access to my app while a user is not signed in.

 <Authenticator includeGreetings={true}>
            <Provider store={dataStore}>
                <Router history={hist}>
                    <MyView>
                    </MyView>
                </Router>
            </Provider>
        </Authenticator>

In my component MyView in the render method I am trying to do a simple auth check by :

if (this.props.authState !== 'signedIn') {
            return (<></>);
        }

But for some reason when checking the auth state in the if condition, it is undefined.

  1. Why is the property undefined - I understood in the docs that it is being down flown to all child components.

    1. Is my approach correct? I saw by the docs that you can implement a method showComponent(theme) and the authenticator will only call it once user is in specific states but I need to set the right states for the authenticator when to call this method by this._validAuthStates = ['signedIn'];

but I don't understand where to call that method, I don't have access to this in any place.

Help will be appreciated.


Solution

  • Not a specialist but I faced this issue and struggle with the doc the same way you seems to.

    I stumble over a solution

    In the index, I render my components that way

        <Provider store={store}>
          <Authenticator
              hide={[SignUp, SignIn, Greetings]}
          >
            <CustomGreetings/>
            <CustomSignUp/>
            <CustomSignIn/>
            <App/>
          </Authenticator>
        </Provider>
    

    In my app component, I now have access to the authState. So I re-inject it in the other components:

    return(
      <Router>
        <NavbarComponent/>
        <Switch>
          <Route path="/dashboard">
            <DashboardContainer authState={this.props.authState}/>
          </Route>
          <Route path="/admin">
            <AdminComponent authState={this.props.authState}/>
          </Route>
        </Switch>
      </Router>
    );
    

    I don't know if it is THE solution but well, for me it works