nuxt-modules / og-image

Generate OG Images with Vue templates in Nuxt.
https://nuxtseo.com/og-image
415 stars 27 forks source link

How to use OgImageDynamic getting data from an API #60

Closed titogarrido closed 1 year ago

titogarrido commented 1 year ago

Details

Hi!

I have a nuxt 3 page that fetches a project data from an external API. This data includes a project cover that I want to set as my OGImage.

I will paste here some snippets and what I am doing:

// This function fetches the project data. 
// The cover value is "project.value.full_cover" that returns a string like http://localhost:9000/projects/image.jpg
async function getProject() {
  await $api
    .get(`/posts/${project_id}`)
    .then((response) => {
      project.value = response.data;
    })
    .catch((error) => {
      console.log(error);
      router.push("/404");
    });
}
// I am calling the getProject() during the Mount
onMounted(async () => {
  await getProject();

I have created a Component on @/components/islands/OgImageWithImage.vue:

<template>
<div>
  <div>
    <img :src="image_path" width="1200" height="630">
  </div>
</div>
</template>

<script setup>
const props = defineProps({
  path: String,
  title: String,
  description: String,
  image_path: String,
})
</script>

The idea is to show my cover image as OGImage.

This is my resumed project component:

<template>
  <LoadingComponent v-if="loading"></LoadingComponent>
  <div v-if="!loading">
  <!-- Project layout goes here -->
  </div>
  <OgImageDynamic
    component="OgImageWithImage"
    title="Hello world"
    :image_path="project.full_cover"
  />
</template

Now I am having trouble to pass this dynamic data to my OgImageDynamic. It does not show up on the "Options" section or it does not update to the fetched value.

What am I missing here?

Thanks!

harlan-zw commented 1 year ago

Hey @titogarrido, thanks for the issue.

Your problem is that you're not loading your project data server-side. The OG image only runs server side so it won't get your project data.

You can fix this simply by getting the project top-level.

<script setup>
const project = await getProject();
</script>
<template>
 <OgImageDynamic
    component="OgImageWithImage"
    title="Hello world"
    :image_path="project.full_cover"
  />
</template>
titogarrido commented 1 year ago

Do you mean I just need to move the Githubissues.

  • Githubissues is a development platform for aggregating issues.