skip to Main Content

In my Nuxt 3 project I have build a server plugin to set meta head tags. In my page/route, I first fetch data from the backend and then call the plugin. The content appears in the html document as expected but the browser console throws an error: Unhandled Promise Rejection: TypeError: $setTags is not a function. (In '$setTags(data.value)', '$setTags' is undefined)

plugins/headTags.server.js

export default defineNuxtPlugin(nuxtApp => {
  nuxtApp.provide("setTags", (data) => {
    const runtimeConfig = useRuntimeConfig();

    useServerSeoMeta({
      // ...
    })

    useServerHead({
      // ...
    })
  });
});

pages/page.vue

<script setup>
const { $setTags } = useNuxtApp()
const { find } = useStrapi4();

const {data} = await useAsyncData(
    "posts",
    async () => {
      const response = await find(...);

      const data = response.data[0].attributes;

      return data;
    }
);
console.log(data) // Contains the data as expected.
$setTags(data.value); // Works but still throws the error. 
</script>

If I move the $setTags() function to the async function before the return statement, the data object will be null.

2

Answers


  1. Chosen as BEST ANSWER

    My mistake. Since I a want to use the plugin server-side only, it is obviously not available client-side and therefore $setTag(...) isn't too. Wrapping the function as follows would fix the issue:

    <script setup>
    ...
    if (process.server) {
      $setTags(data.value);
    }
    </script>
    

  2. It seems that the injected function is not available at the creation time, try to add condition before running it:

    if($setTags){
      $setTags(data.value);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search