-1

I've create an array of objects "postsList" that contains information as I was able to log to console.

var postsList = [];
var postsCollection = new wp.api.collections.Posts();
postsCollection.fetch({
    data: {
         per_page: 20
    }
}).done(function( posts ) {
    postsCollection.each( function( post ){
        //console.log( post.attributes );
        postTitle = post.attributes.title.rendered;
        postID = post.attributes.id;
        postsList.push({
            id: postID,
            title: postTitle
        });
    });
});
console.log(postsList); // this works
console.log(postsList[0].id); // this doesn't work - Undefined

But, when I try to access individual pieces of it, my console says that it is undefined.

Can you help me understand what I'm doing wrong? Here is my console.log output with "console.log(postsList);":

[]
0:
    id: 306
    title: "Another Post"
    __proto__: Object
1:
    id: 1
    title: "Hello world!"
    __proto__: Object
length: 2
__proto__: Array(0)
LKD
  • 1
  • 1

1 Answers1

1

You should log the data in the done callback. The "A" in AJAX stands for asynchronous, which means that the rest of the code will execute without waiting for the AJAX call to finish. In your case, your are trying to log the data before the AJAX call is finished.

var postsList = [];
var postsCollection = new wp.api.collections.Posts();
postsCollection.fetch({
    data: {
         per_page: 20
    }
}).done(function( posts ) {
    postsCollection.each( function( post ){
        //console.log( post.attributes );
        postTitle = post.attributes.title.rendered;
        postID = post.attributes.id;
        postsList.push({
            id: postID,
            title: postTitle
        });
        console.log(postsList);
        console.log(postsList[0].id);
    });
});
Unmitigated
  • 76,500
  • 11
  • 62
  • 80