0

I'm trying to push to the end of array a new value when onSubmit event is raised. My code looks like this:

  accounts: Account[] = [];
  feeAccount: Account = new Account();

  onSubmit(f: FormsModule) {
    console.log('Fee account -> ' + this.feeAccount);
    this.accounts.push(this.feeAccount);
  }

The problem is that I'm getting an error: Cannot read property 'push' of undefined. in spite of correct value logged just before it tries to push. What could be wrong here? I believe it is defined if it is logged correctly in the same method, or am I getting something wrong?

1
  • Check that you're not accidentally mutating accounts, it appears to be correctly defined in the code above but if you're getting that error it suggests that it can't access this.accounts suggesting it's been changed to undefined from an empty array. Commented Apr 24, 2020 at 11:33

1 Answer 1

1

It seems that, in somewhere in your code, you are assigning another type to accounts variable or mutating it acciendally which is obviously not array anymore

add console.log to debug accounts object on submit action

console.log(this.accounts);
console.log(typeof this.accounts);

will give you clear idea

Sign up to request clarification or add additional context in comments.

4 Comments

The type wouldn't cause the error as JS doesn't actually have type checking when it's run. The error is caused b/c somewhere the value of this.accounts has been changed, not the type :)
I am not talking about type checking. but the type is actually changing from array to something else. Author is defined it as array but it is not anymore. it is something else like null, undefined, object or vs
@DervişKayımbaşıoğlu it is undefined, but shouldn't it be undefined because now I'm trying to define it?
@DervişKayımbaşıoğlu sounds like a minor variance of semantics with value vs type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.