Home  >  Q&A  >  body text

Nested useFetch in Nuxt 3

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粉590929392P粉590929392207 days ago538

reply all(2)I'll reply

  • P粉505917590

    P粉5059175902024-03-26 17:52:53

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

    sssccc
    

    reply
    0
  • P粉561323975

    P粉5613239752024-03-26 13:55:31

    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
    
    

    reply
    0
  • Cancelreply