Nuxt useFetch/useAsyncData twice in method throws error: `nuxt instance not available`
Asked Answered
I

2

0

I encounter the classical nuxt instance not available error when server side rendering a nuxt page containing the following logic:

<script setup>
const getImageOne = async () => {
  return await useFetch('https://dog.ceo/api/breeds/image/random');
};

const getImageTwo = async () => {
    return await useFetch('https://dog.ceo/api/breeds/image/random');
};

const getImages = async () => {
  return [await getImageOne(), await getImageTwo()];
};

const responses = await getImages();
const dogOne = responses?.[0]?.data?.value;
const dogTwo = responses?.[1]?.data?.value;
</script>

<template>
  <div>
    <p>Dog 1: {{ dogOne }}</p>
    <p>Dog 2: {{ dogTwo }}</p>
  </div>
</template>

The issue seems to be that useFetch is called twice in one method call.

Innards answered 17/4, 2023 at 8:29 Comment(0)
I
3

The issue with composable usage raising nuxt instance not available errors is already well known, see issue #14723 for reference.

A solution in this case would be to use the callWithNuxt method and provide the nuxt instance manually like this:

<script setup>
import { callWithNuxt } from 'nuxt/app';

const getImageOne = async () => {
  return await useFetch('https://dog.ceo/api/breeds/image/random');
};

const getImageTwo = async (app) => {
  👇
  return await callWithNuxt(
    app,
    async () => await useFetch('https://dog.ceo/api/breeds/image/random')
  );
};

const getImages = async () => {
  👇
  const app = useNuxtApp();
  return [await getImageOne(), await getImageTwo(app)];
};

const responses = await getImages();
⋮
Innards answered 17/4, 2023 at 8:34 Comment(0)
D
0
export default defineNuxtConfig({
  experimental: {
    asyncContext: true
  }
})
Denazify answered 30/8 at 18:13 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions applyFormulaic

© 2022 - 2024 — McMap. All rights reserved.