-2

am trying to handle undefined error in JavaScript
the console is dumping this error

Uncaught TypeError: Cannot read property 'data' of undefined

my code :

try { 

FB.api(
  '/me/',
  'GET',
  {"fields":"posts{likes.limit(10){id,name}}"},
  function(response1) {

console.log(response1);
response1.posts.data[1].likes.data[0].id
if (typeof(response1.posts.data[1].likes.data[0].id) == 'undefined') { 

alert("error1");
}

});


} 
catch(err) { 

alert("erro2");

} 

what am doing wrong ?

  • `response1.posts` might not be defined. What does `console.log(response1)` show you? – John Bupit Dec 27 '15 at 13:26
  • Array with ids and names I know `response1.posts.data[1].likes.data[0].id` is undefined but I need to handle that error – Hyper codes Dec 27 '15 at 13:35
  • Please format/indent your code. Also, is this still relevant? http://stackoverflow.com/questions/3335977/accessing-data-from-response-of-fb-api –  Dec 27 '15 at 13:36
  • 1
    in first place, you are doing javascript wrong having async operation inside of ```try-catch``` block. callback is called when ```try-catch``` block is over – Srle Dec 27 '15 at 13:43

2 Answers2

1

you're trying to get some data from a chain of objects where an object before your object is undefined, so explicitly you're trying to call undefined.data. this is why your if-condition is not fullfilled and you're getting just your normal console error instead of your alert (which is desired here, as I understand your code).

Instead, you could do something like this:

    if (typeof(response1.posts) && typeof(response1.posts.data[1].likes.data[0].id) == 'undefined') 
{...} 
Dominik
  • 2,801
  • 2
  • 33
  • 45
  • still the same error – Hyper codes Dec 27 '15 at 13:37
  • 1
    try using typeof on response1 for example, and change the condition as it fits your case. my answer just contains an example which (i think) will not do exactly what you desire, but should give you a clue what is going wrong and how you could fix it. Please see @torazaburo 's link in his comment on your question, too, which may be relevant. – Dominik Dec 27 '15 at 13:42
0

Could be the response is not an Object, but a string. Try converting it to JavaScript Object:

console.log(response1);
response1 = JSON.parse(response1);
response1.posts.data[1].likes.data[0].id
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252