Fetching related data sequentially
I'm working on a nuxt 3 app at work and our backend returns relational data as ids that I need to fetch if I want to display it. For example let's say we're building a blog, the interfaces would look something like this
Now let's say I want to display a list of posts with informations about their authors on a page. I'd first fetch the posts with something like
Then i would have to fetch the authors based on the ids contained in
posts
so something like
But this won't work since the second request would fire immediately, so posts.value.map
would fail or return an empty array.
I could to this in the transform
of the first useAsyncData
, fetching my relations once I have the base data, but this would cause issues the moment the relations I'm fetching have relations of their own...
So I'm wondering how you folks would do it ?4 Replies
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
The direction I've been leaning in is to create a composable that takes an array of urls. In the composable, you make all your requests with an
await Promise.all
. You can expose similar statuses to the useFetch compsable (e.g. pending, error, data). Data can then contain an object of all your records - e.g. { posts: [...], authors: [...], comments: [...]}Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Sounds like a good start towards what I want, I'll have to make some changes to meet my business requirements but I think it could work thanks
This works fine no problem, the issue I have is for fetching the "secondary" data, I need to know which posts I get before I fetch their authors, and this can be achieved through a watcher but can become cumbersome if there's a lot of nested relations to fetch like user > comments > posts > authors for example.
The solution from Woutercouvaras looks more like something that would work for me, chaining promises to fetch all the nested data based on an array of urls.