Setting useSeoMeta from Async Data

21 Views Asked by At

I have this code where I fetch from my Sanity CMS. I'm looking to set the useSeoMeta so that the title is the title from Sanity's Data.

const { data } = useAsyncData('category', () => sanity.fetch(
  query, { categoryId: route.params.id }
));

useSeoMeta({
      data,
      description: () => `${data.value[0].description}`,
      title: () => `${data.value[0].title} Card Prices & List`,
});

The issue I have is, on first click the page does not load, then second click the page loads with the title/description loaded in. On first click, I get the usual TypeError: Cannot read properties of null (reading '0') on data as it hasn't been loaded in yet.

1

There are 1 best solutions below

3
Ilijanovic On

You could try to use a placeholder while it loads

const { data } = useAsyncData('category', () => sanity.fetch(
  query, { categoryId: route.params.id }
));

useSeoMeta({
      data,
      description: () => `${data.value?.[0].description ?? 'Loading...' }`,
      title: () => `${data.value?.[0].title ?? 'Loading' } Card Prices & List`,
});

Or you try to use top level setup

<script setup>
const { data } = await useAsyncData('category', () => sanity.fetch(
  query, { categoryId: route.params.id }
));


useSeoMeta({
      data,
      description: () => `${data.value[0].description }`,
      title: () => `${data.value[0].title } Card Prices & List`,
});

</setup>