Noriaki Takamizawa
Noriaki Takamizawa

Reputation: 1039

A composable that requires access to the Nuxt instance was called outside of a plugin

I'm creating microcms app using nuxt3. And I bumped into the error which I wrote in title. I know it might be component problem, but I can't figure out why. Here's the code.

pages/list.vue

<template>
    <div class="flex flex-col">
        <div>
            <h1 class="m-3 text-4xl font-bold">当店のレビュー一覧</h1>
        </div>
        <ReviewList :reviews="reviews.contents" />
    </div>
</template>

<script>
    const {data:reviews} = await useFetch('/api/reviewList')
</script>

components/ReviewList.vue

<script setup lang="ts">
    import { Review } from '../types/review'

    const header = ref(["number", "title"])

    type Props = {
        reviews: Review[];
    }

    const { reviews } = defineProps<Props>()
</script>

<template>
    <table>
        <thead>
        <tr>
            <th class="p-1" v-for="col in header">{{ col }}</th>
        </tr>
        </thead>
        <tbody>
            <tr class="hover:bg-green-200" v-for="(review, index) in reviews">
                <th class="p-1">{{ index+1 }}</th>
                <nuxt-link :to="`/${review.id}`">
                    <td class="p-1">{{ review.title }}</td>
                </nuxt-link>
            </tr>
        </tbody>
    </table>
</template>

types/review.ts

import type { MicroCMSListContent } from "microcms-js-sdk";

export type Review = {
    title: string;
    body: string;
} & MicroCMSListContent;

server/api/reviewlist.ts

import client from './client'
import { Review } from '../../types/review'

export default defineEventHandler(async (event) => {
    const data = await client
        .getList<Review>({
            endpoint: 'reviews',
        })
    return data
})

server/api/client.ts

import { createClient } from 'microcms-js-sdk';

const ctx = useRuntimeConfig();

const client = createClient({
    serviceDomain: ctx.serviceDomain,
    apiKey: ctx.apiKey,
});

export default client

What's wrong? Please tell me how to fix it. Thanks in advance.

Upvotes: 5

Views: 15059

Answers (2)

JimKenly
JimKenly

Reputation: 11

Today I'm going to show you how to fix the problem using useFetch() is a composable method.

watch(router,(value) => {
  useFetch("/list");
})

Afterwards, I had to use:

const LoadPage = () => {
  useFetch("/list");
}

------ how to fix methods ---

loadPage go to the top to view and call again

watch(router,(value) => {
  loadPage();
})

This article helped me understand the reason why using a function of composable is wrong position

Upvotes: 1

Noriaki Takamizawa
Noriaki Takamizawa

Reputation: 1039

I finally figure it out.

<script>
    const {data:reviews} = await useFetch('/api/reviewList')
</script>

When I changed the code above to below, it works.

<script setup lang="ts">
    const {data:reviews} = await useFetch('/api/reviewList')
</script>

Upvotes: 5

Related Questions