44

I have this error in my terminal:

TypeError: Cannot read properties of undefined (reading 'id')

I'm trying to test the call to an API, but the error appears.

My function:

itemToForm = () => {
    this.api.send(this.component, 'get',
        { lang: 'ES', filter: { id: this.item['id'] } }
    ).then(resEsp => {
        this.item = resEsp['data'][0];
        this.api.send(this.component, 'get',
            { lang: 'EN', filter: { id: this.item['id'] } }
        ).then(res => {
            let itemEng = res['data'][0];
            let fields = this.formDef.map(register => register.filter(
                field => field['register_table'].indexOf('traduction') !== -1
            ).map(
                field => field['field_name'])
            ).filter(register => register.length);

            fields = fields.length ? fields[0] : [];

            if (itemEng) {
                this.item = Object.keys(itemEng).reduce((obj, key) => {
                    obj[key] = this.item[key];
                    if (fields.indexOf(key) !== -1) {
                        obj[key + '_eng'] = itemEng[key];
                    }
                    return obj;
                }, {});
            }

            if (this.item) {
                this.setForm();
            }
        })
    })
}

My specification file:

it('should call api.send', () => {
    let spy1 = spyOn(api, 'send');
    let item = {
        id: 1,
        name: 'test',
    }

    component.addItem(item);
    component.itemToForm();

    expect(spy1).toHaveBeenCalled();
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
David Angarita
  • 740
  • 4
  • 8
  • 15
  • 1
    seems like `this.item` isn't initialized yet in line 2 of your snippet. Or `resEsp['data']` doesn't contain any elements, thus `this.item = resEsp['data'][0];` will set `this.item` again to undefined, which will throw an error in line 4 of your snippet. – derpirscher Aug 27 '21 at 22:10
  • an index.ts file might also be the culprit. try to import directly (without using index.ts files) and see if the error resolves. – Wolf359 Sep 25 '21 at 13:39

5 Answers5

25

What is happening:

The function itemToForm() is being called before the this.item is ready.

There are many strategies to avoid this error. A very simple one is to add a catcher at the beginning of the function, like this:

itemToForm = () => {
  if(this.item === undefined) {return}
         
  // The rest of the code
}

This stops the function, if the data does not exist yet.

A more elegant solution may be to go further up in your order of operations, and find who is calling itemToForm() and ensure the data exists prior to calling.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Izzi
  • 2,184
  • 1
  • 16
  • 26
  • 1
    Perfect! On Vue - with Vuetify - the issue occurs inside the library when we use a watch. Your solution protect from the problem. Thanks! – Michel Fernandes Apr 29 '22 at 21:55
12

I bumped to this question but my issue was actually something completely different.

In my code for some reasons I had

import { SOME_OBJECT } from '.';

which should instead be like this:

import { SOME_OBJECT } from './proper-file';
Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252
  • Same here. Angular was blowing up in a random component saying cannot read property of undefined. Turns out, the import path was wrong. – khollenbeck Jun 13 '22 at 22:43
1

I got the error "Cannot read properties of undefined (reading 'spec')" when attempting to install a local npm module with npm install [path to module here].

The source of the problem: I hadn't given the local module a name in its package.json file.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Raffi
  • 970
  • 11
  • 13
1

In my case, the error was similar, but I got a different solution as I was using the body-parser module in the JavaScript file.

I had to add

app.use(bodyParser.urlencoded({ extended: true }));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

Typescript version error in package.json change typescript version to,

"typescript": "3.8.3"

then npm install