0

I'm running an axios ajax call within a for object loop that is also within another axios ajax call. The parent object seems to be available within the the internal axios function, but specifying the object within the loop with [i] returns undefined. Here is my current code:

// GET NEXT PAGE OF POSTS
      axios.get(`https://rootdomain.co.uk/cms/index.php/wp-json/wp/v2/posts?offset=1&per_page=4&page` + this.currentPage)
        .then(function (response) {
          var additionalPosts = response.data
          // var additionalPostsThumbnails
          // SET FEATURED IMAGE AND THUMBNAIL KEY AND VALUE
          for (var i = 0; i < additionalPosts.length; i++) {
            const featuredImageAPI = 'https://rootdomain.co.uk/cms/index.php/wp-json/wp/v2/media/' + additionalPosts[i].featured_media
            axios.get(featuredImageAPI).then(response => {
              console.log(additionalPosts)
              console.log(additionalPosts[i])
            })
          }
          // REMOVE 'is-loading' CLASS TO BUTTON
          button.classList.remove('is-loading')
        })

So console.log(additionalPosts) is working, but console.log(additionalPosts[i]) is returning undefined. Any ways around this?

Once I can access the specific object the aim is to add another key and value to the individual objects.

Appreciate any help. Thanks!

  • is the var additionalPost an array, can you provide a sample – Jarek Kulikowski Jul 21 '17 at 15:32
  • You're getting undefined probably because `axios.get` is async, and by the time response is received, the variable `i` may not have the same value. Why do you need `additionalPosts[i]` in the response? – Nisarg Shah Jul 21 '17 at 16:09
  • additionalPosts are javascript objects, retrieved from the the WordPress REST api. – Anthony Collins Jul 21 '17 at 20:00
  • I need to create a new item in each object pointing to their respective featured media, but i can only get the featured media source url by making another api call. So i need additionalPost[i] to I can make the call to the correct featured media. I hope that make sense! – Anthony Collins Jul 21 '17 at 20:04

0 Answers0