First of all: I don't exactly know where to place this question. If wrongly placed, a hint on where to post would be nice :)
The problem:
In my API-enabled backend I have a series of post categorized by year. Uitlizing asyncData and using axios I want to fetch these posts based on the various years; thus return all posts from 2017, posts from 2016, etc. as separate items in a collected array.
I can make a call to return all available years (http://api.template-studio.nl/wp-json/wp/v2/categories?parent=19). In my theory I should then loop over the years and return the post-content year by year (http://api.template-studio.nl/wp-json/wp/v2/werkitem_nl?categories=+yearId).
Here's a draft on what I'm working on:
async asyncData({
params,
query,
error
}) {
let [recursiveCategoryDataRes] = await Promise.all([
// GET ALL THE CATEGORIES (YEARS) WITHIN THE 'YEAR'-CATEGORY PARENT
axios.get('http://api.template-studio.nl/wp-json/wp/v2/categories?parent=19').then((res) => {
// LOOP OVER THE RETURNED CATEGORIES (YEARS) AND GET THEIR RELEVANT POST-CONTENT ONE BY ONE. PUSH TO EMPTY ARRAY.
var recursiveData = []
for (var i = 0, len = res.data.length; i < len; i++) {
var yearId = res.data[i].id
axios.get('http://api.template-studio.nl/wp-json/wp/v2/werkitem_nl?categories=' + yearId).then((resNested) => {
recursiveData.push([resNested.data[0].categories[0], resNested.data])
})
}
// RETURN THE COLLECTED data
return recursiveData
})
])
return {
recursiveCategoryData: recursiveCategoryDataRes,
}
}
This method seems to somewhat work, but is not always returning the recursively-gathered content fully. As if the script ends before all recursive calls have been made.
Any suggestions on how to handle nested/recursive calls within asyncData?
All the best
Lasse
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c1625">#c1625</a>)</em></sub></div>