1

I use the oberserver pattern to listen for a variable. At first the incoming object is undefined. If this is the case, further functions should not be executed. Only if the object is not undefined, the functions should be executed. I have tried many things like if(a !== undefined), if(typeof a != 'undefined'), ... I always get the same error in the line a.prop.find() or in the if statement itself.

Cannot read property 'a' of undefined

How can I check correctly?

A.class

const a = state.find(state => state.id === this.id);
return a;

B.class

this.val.subscribe((a) => {
  // Check if a is undefined
  a.prop.find(...);
}
laprof
  • 1,246
  • 3
  • 14
  • 27
  • in `A.class` this line `state.find(state => state.id === this.id)` is probably returning undefined, so when it gets to `b.class` your looking at undefined. – Get Off My Lawn Mar 14 '20 at 02:35
  • in your subscribe callback please put an example of how you are writing your if statement (including the body of the statement). – Get Off My Lawn Mar 14 '20 at 02:41

1 Answers1

0

If you're getting an error like:

Cannot read property 'a' of undefined

That means, you're trying to access the property a of an undefined object.

What you're doing here is checking if a is undefined. But what you should be doing is checking if the object, from which you're trying to access the property a, is undefined.

From the code you've posted, it doesn't seem the error is present there. Look where ever you're trying to access the property a and you'll find the root cause.

For example:

// An undefined object
let obj = undefined;

// Now if you try to access any property of `obj`
obj.a;

This will throw:

TypeError: Cannot read property 'a' of undefined
Traction
  • 311
  • 3
  • 6