directus-labs / examples

Integration Examples with Directus
https://directus.io/guides
MIT License
257 stars 113 forks source link

useAsyncData example for static generation #162

Closed ckald closed 2 years ago

ckald commented 2 years ago

How one would use directus API to generate a completely static site using Directus? Simple html/js files that do not trigger backend requests.

I'm trying to implement the following:

export const asyncDirectusItems = async (key, config, transform) => {
  const { getItems } = useDirectusItems();
  const { data } = await useAsyncData(key, async () => await getItems(config), {transform});
  return data;
};

export const asyncDirectusItemById = async (collection, id, transform) => {
  const { getItemById } = useDirectusItems();
  const key = `${collection}#${id}`;
  const { data } = await useAsyncData(key, async () => await getItemById({ collection, id }), {transform});
  return data;
};

But recent Nuxt 3 RC's (9 and 12) either fail to generate directly accessible SSR pages or mix their markup with the front page. Also I'm having trouble to prevent Directus API calls (which are unnecessary for a completely static website).

<script setup>
const categories = await asyncDirectusItems('blog_categories', {
  collection: "Blog",
  params: {
    fields: "category",
    groupBy: "category"
  }
});

const posts = await asyncDirectusItems('published_blogs', {
  collection: "Blog",
  params: {
    filter: {
      status: "published"
    }
  }
});
</script>
rijkvanzanten commented 2 years ago

I think this is more of a Nuxt usage question than a Directus specific question right? The answer to this question should be the same regardless of what API you're requesting the data from 🙂 (I don't use / know Nuxt 3 RC, so that's about as much info as I can provide..)

ckald commented 2 years ago

Oh sorry, I confused this repo with nuxt-directus! Because this one contains the example app