Nested useFetch in Nuxt 3
P粉590929392
P粉590929392 2024-03-25 18:44:17
0
2
610

How to complete nested fetching in Nuxt 3? I have two APIs. The second API must be triggered based on the value returned by the first API.

I tried the code snippet below but it doesn't work because page.Id is null when called. I know the first API returns valid data. So I guess the second API is triggered before the first API returns the result.

<script setup>
  const route = useRoute()
  const { data: page } = await useFetch(`/api/page/${route.params.slug}`)
  const { data: paragraphs } = await useFetch(`/api/page/${page.Id}/paragraphs`)
</script>

Obviously this is a simple attempt as there is no check whether the first API actually returns any data. It doesn't even wait for a response.

In Nuxt2, I would put the second API call inside .then(), but I'm a bit stuck with this new Composition API setup.

P粉590929392
P粉590929392

reply all(2)
P粉505917590

One solution is to avoid using await. Also, use references to hold values. This will make your UI and other logic reactive.

sssccc
P粉561323975

You can watch the page and then run the API call when the page is available, you should pass the paragraphs as ref and then assign the destructured data:

sssccc

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template