AmplifyJS is throwing an error: TypeError - It seems like the property 'state' is undefined and cannot be read

I am currently working on integrating the steps outlined in the Amplify walkthrough with an Angular cli application.

  • My app is a brand new Angular cli project following the mentioned guide.

  • My objective is to utilize the standalone auth components as described in the link above.

  • However, I encounter an issue when attempting to include

    <amplify-auth-sign-up></amplify-auth-sign-up>

The error message displayed: https://i.sstatic.net/aRrCa.png

In my Component, I have set up the required state as indicated in the provided walkthrough.

auth.component.ts

import { Component, OnInit } from '@angular/core';
import { AmplifyService } from 'aws-amplify-angular';

@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.css']
})
export class AuthComponent implements OnInit {

  constructor(private amplifyService: AmplifyService) {
    this.amplifyService.setAuthState({
      state: 'signUp',
      user: null
    });
  }
}

auth.component.html

<amplify-auth-sign-up></amplify-auth-sign-up>

Any assistance would be greatly appreciated. Feel free to ask any questions or provide additional information if needed.

Answer №1

The code snippet below successfully enabled the functionality I was seeking. It became evident that individual components within Amplify necessitate a state to be defined, which I accomplished by utilizing "authState" as depicted below. The distinction lies in explicitly specifying the state both in the HTML and TypeScript.

By setting the authState (including user: null, state: 'signUp' as shown), the error can be eliminated, allowing the sign-up form to display.

In this code snippet, additional elements have been incorporated to illustrate further how authState can be utilized.

Upon execution, the page will initially load with the sign-up form visible.

After the user inputs their details and clicks on sign up, the page transitions to displaying the "confirm sign up" form. This stage requires the user to enter a verification code sent by Cognito (depending on your configuration):

HTML:

    <amplify-auth-sign-up [authState]="authState" *ngIf="showSignUp"></amplify-auth-sign-up>
    <amplify-auth-confirm-sign-up [authState]="authState" *ngIf="showVerify"></amplify-auth-confirm-sign-up> 

TS:

    import { AmplifyService } from 'aws-amplify-angular';
    import { AuthState } from 'aws-amplify-angular/dist/src/providers';

    Export class AuthComponent implements OnInit {

    public authState: AuthState
    public newUser: any
    public state: any
    public showSignUp = true
    public showVerify = false

    constructor(public amplifyService: AmplifyService) {
         this.authState ={ //specifying this is adequate for displaying the sign-up form and resolving the error
           user: null,
           state: 'signUp' 
         }

         this.amplifyService.setAuthState(this.authState)  //this step may not be necessary

         this.amplifyService.authStateChange$ //tracking state changes. For instance, if post-submit action needs to be taken after the user signs up
                .subscribe(authState => {   
                    this.state = authState.state
                    this.newUser = authState.user
                    if (this.newUser){ //an illustration of extracting data from the stateChange. Optional.
                      this.username = this.newUser.username
                    }

                    if (this.state === 'confirmSignUp'){//monitoring state change
                       this.authState ={
                          user: authState.user,
                         state: 'confirmSignUp'
                       }
                       this.showSignUp = false
                       this.showVerify = true
                    }
                }
     }
 }

For more insights on aspects like automatic sign-in, refer here.

A noteworthy observation is that Amplify components may display error messages containing technical information not intended for users. Customization options might exist (discussed here); however, rigorous testing across various scenarios is advisable to anticipate potential error prompts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging the Firebase email trigger extension with JavaScript

Recently, I integrated the email trigger extension for Firebase. Below is the function I am using: firestore .collection("profiledata") .doc(user.uid) .update({ accountStatus: "active", }) .then(() => { // At this p ...

Creating a Related Entry in strapi v4: A Step-by-Step Guide

Whenever I try to add a new record in my Collection-Type, all the field values are successfully added to the new entry except for the value in the field with a Relation type. For instance, in my event Collection-Type, I have fields like name, performers, ...

Vue JS: dynamic reactive structure

As I delved into understanding the basics of reactivity and its syntax, I encountered an interesting problem. Take a look at this code snippet: const app = Vue.createApp({ data: dataFunction, methods: {method1: methodImpl} }) var dataObj = { tit ...

How to Retrieve Information from an Array in VueJS

At the moment, the data being displayed on my page is an array, as shown in the snippet below: https://i.stack.imgur.com/zAvrc.png However, I only want to retrieve or display the project names. This is all I have at the moment: fetch(context,id){ ...

What is the best way to include a new attribute in a TypeScript internal object?

I am trying to include a property declaration in the window.history object, but I received a TypeScript error message This is my code: const historyInstance = createHashHistory(); // npm hoistory module window.history.historyInstance = historyInstance; / ...

"Encountering a problem with using setState in React Hook useEffect

I am currently utilizing the useState hook with two arrays: imageList and videoList. In my useEffect hook, I iterate through the data using forEach method. If the type of the item is an image, it should be pushed to the imageList array. However, after exec ...

The child component is not updating the v-model prop array of the parent component

In my current project, I have a main component called cms-custom-editor: <template> <div id="cms-custom-editor" class="cms-custom-editor"> <cms-editor-toolbar v-model:toggles="state.toggles"/> <d ...

Utilizing conditional statements in React js to showcase a distinct component

I am looking to create a function or conditional statement that dynamically displays different components based on whether the user has purchased products. If the user has bought products, I want to display the product components; if not, I would like to s ...

Efficiently managing multiple database updates with PHP and JQuery

Having trouble processing multiple mySQL updates simultaneously? I have 4 select/option boxes fetching data from a db table and I want to update the database onChange using JQuery. It's working with one select module, but adding more causes issues. Th ...

retrieve data types from an array of object values

I am looking to extract types from an array of objects. const names = [ { name: 'Bob' }, { name: 'Jane' }, { name: 'John' }, { name: 'Mike' }, ] The desired result should resemble thi ...

Delving into the World of CSS

I have been working on changing the background image using this JavaScript code, but I am not sure what to reference in the CSS file. Despite reading through everything, my screen still remains blank. $(function() { var body = $('body'); var bac ...

Troubleshooting problems with bot roles on Discord

After spending some time coding my bot, I encountered an issue when trying to add a role to a user who didn't already have it. Everything seemed to be functioning properly until I included the member.roles.add command. Despite having every possible p ...

Update Button Colour upon clicking the Button

I have multiple buttons lined up in a row on my webpage. I want the button's color to change when I click on them. Below is a snippet of my code: $( "button.change" ).click(function() { $(this).toggleClass( "selected" ); }); .Button { font-fa ...

How is it possible to retrieve the flex-direction property value of a div using JavaScript?

While attempting to troubleshoot this issue using Windows Chrome 59, I utilized devtools to examine the properties. let element = document.getElementById("divId"); Upon checking the value of the element, I noticed that the object structure displayed: &g ...

How to fetch and display images using Vue.js with Axios and a web API

I have managed to successfully upload an image using axios and can preview it in Postman. However, I am unsure of how to proceed with rendering the image in vuejs. Implementing the Get Method: public HttpResponseMessage FetchImage(int id) { ImageServ ...

An unexpected page transition occurs when attempting to delete a link

I've successfully created an HTML table that dynamically adds rows and provides an option to delete the current row. Each row represents data retrieved from MongoDB, and upon clicking the delete button, I aim to delete the corresponding item from the ...

Align watermark content to the far left side

Having trouble getting my watermark to align properly on the left side of my website's main content. Here is how it currently looks: The issue arises when I resize the screen or switch to mobile view, as the watermark ends up covering the main conten ...

Exploring: Strategies for patiently waiting for a webpage to refresh

Exploring Angular 15 with karma and jasmine When I navigate from one page to another by clicking a button, the TD tags on the new page are not being displayed in my tests. beforeEach(async () => { await TestBed.configureTestingModule({ decla ...

Find and extract elements from a nested array within an object inside another object within an array of objects

I am working with an array of objects that looks like this: [ { likes: [], _id: 5f254e21fd3e040640de38b2, content: 'try this', author: { posts: [Array], comments: [], images: [], followers: [Array], ...

If the variable is not defined, then utilize a different one

There are two scopes: $scope.job and $scope.jobs. I also have a variable called job; If $scope.job is undefined, I want $scope.jobs to be assigned to the job variable using the following code: var job = $scope.jobs. However, if $scope.job is defined, the ...