0

I have a function that happens on the lifecycle event ngOnChanges, now the function works fine but when the app first loads it throws an error ERROR TypeError: Cannot read property 'fields' of undefined now I know the reason is because the data its trying to read the property from hasn't arrived yet but then obviously when the data is there it works.. this is my function

 ngOnChanges(changes: SimpleChanges) {
    this.contentfulService.getWeekItems(this.item.fields.week)
      .then((weekItems) => {
        this.weekItems = weekItems;
      }).then(() => {
        this.numberOfItems = this.weekItems.length;
  });
 }

now I know if I was in my component.html I could do something like this.. "item?.fields?..." is there an equivalent for inside your .ts file?

swetansh kumar
  • 475
  • 7
  • 17
Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152
  • you can check if the property `fields` exists or not? https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object – swetansh kumar Mar 22 '18 at 06:25
  • @swetanshkumar The property fields does exist, but the item hasnt been returned yet, thus when the page is loaded the first 'change', there is nothing there which is why the error is being called and then on the next change when the data has come back obviously the error goes away – Smokey Dawson Mar 22 '18 at 06:30
  • that is why I told you to add a check if value exists ? This will prevent the console from throwing error as `undefined`. – swetansh kumar Mar 22 '18 at 06:32
  • @swetanshkumar could you explain how I apply this in my situation? – Smokey Dawson Mar 22 '18 at 06:37
  • `this.numberOfItems = this.weekItems && this.weekitems.length` unfortunately there is no null coalescing operator in typescript – Jim Mar 22 '18 at 06:41
  • @Jim how does that solve my problem? – Smokey Dawson Mar 22 '18 at 06:42
  • 1
    it doesn't sorry, I did not read carefully enough, I will come back with a better suggestion. what does your html look like? can you not just check whether or not `item.fields` exists in an `if` statement before calling `getWeekItems` – Jim Mar 22 '18 at 06:43

1 Answers1

2

There is no Null coalescing operator in typescript yet. Refer: https://github.com/Microsoft/TypeScript/issues/16

However,

this.item?.fields is equivalent to this.item && this.item.fields

gawicks
  • 1,894
  • 15
  • 22