I´m creating a static site using @nuxt/content
and I´m trying to create some components that will be used from the markdown. One of those components needs to call external API to retrieve some data that is shown in the HTML.
These are the relevant snippets, trying to show a card with information from a GitHub repository:
blog_article.md
In <content-github-repository repo="jgsogo/qt-opengl-cube">this repository</content-github-repository> there is...
content/github/Repository.vue
<template>
<span class="">
<a :href="`https://github.com/${repo}`">
<slot>{{ repo }}</slot>
</a>
<div>{{ info.description }}</div>
</span>
</template>
<script>
export default {
props: {
repo: {
type: String,
require: true,
},
},
data: () => ({
info: null,
}),
async fetch() {
console.log(`Getting data for repo: ${this.repo}`);
this.info = (await this.$axios.get(`https://api.github.com/repos/${this.repo}`)).data;
},
};
</script>
The error I get is Cannot read properties of null (reading 'description')
, it is like the this.info
is not being populated before rendering the HTML... but it runs, because I get the output from the console.log. Maybe I misunderstood the docs about fetch
, is there any other way to achieve this behavior?
Thanks!
CodePudding user response:
Check out the docs here. From the looks of it, Nuxt can mount the component before fetch
finishes, so you need to guard against that data
not being set when accessing it in your component.
Something as simple as the following should work:
<template>
<span class="">
<a :href="`https://github.com/${repo}`">
<slot>{{ repo }}</slot>
</a>
<p v-if="$fetchState.pending">Fetching info...</p>
<p v-else-if="$fetchState.error">An error occurred :(</p>
<div v-else>{{ info.description }}</div>
</span>
</template>