Cdevelop
Cdevelop

Reputation: 65

How to prerender content with Nuxt Js from own Api?

I have a Vuex store

/store/articles.js

export const state = () => ({
  article:'',
})
export const mutations = {
  setArticle(state, payload) {
    state.article= payload.data;
  }
}
export const actions = {
  async getArticle ({ commit }, id) {
    try {
      const { data } = await axios.post('http://test.local/api/getArticle',id);
      commit('setArticle', { data })
    } catch (e) {
      console.log(e);
    }
  }
}

my API returns a JSON like example this

{
  "id": 1,
  "title": "some title",
  "content": "some content",
  "image": "article_img1.jpg"
}

there is my page and content from API

/pages/article/slug.vue

<template>
  <div> 
    <h4>{{ article.title }}</h4>
    <img :src="'/images/'+article.image" />
  <div v-html="article.content" />
  </div>
</template>

<script>
export default {
  computed:{
      article(){
        return this.$store.dispatch('getArticle',1)
      },
  },
}
</script>

Content appears fine, but when I look at the content page code, there is no content. How to make the content prerendered, on this way?

And how to generate static pages from an API, do I need to use @nuxt/content ? I am trying this, but it looks like works only from .md or .json files, I don't understand how to generate automatically with some API fetching.

Upvotes: 4

Views: 1874

Answers (3)

Cdevelop
Cdevelop

Reputation: 65

async asyncData({params, store}) {
      articles: await store.dispatch('articles/articlesById', {'id': params.id, 
      return {articles};
    },

this works

and i make ssr true in config

Upvotes: 0

Borjante
Borjante

Reputation: 10477

Use the nuxt asyncData hook for that.

<template>
  <div> 
    <h4>{{ article.title }}</h4>
    <img :src="'/images/'+article.image" />
  <div v-html="article.content" />
  </div>
</template>

<script>
export default {
  computed: {
      articles() {
          return this.$store.state.article
      }
  },
  async asyncData() {
      await this.$store.dispatch('getArticle',1)
  },
}
</script>

This will make nuxt wait on the server for the promise to resolve.

Upvotes: 1

kissu
kissu

Reputation: 46604

You can totally generate pages from an API without the need of nuxt/content. I have written an in-depth answer here: Rewriting to a 404 page doesn't work if the page doesn't exist on a site created with SSG in Nuxt.js

Showing how to achieve a clean generation of your pages during build time.
Otherwise, you can also follow the steps described into the documentation here: https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-generate#function-which-returns-a-promise

Also, be sure to have ssr set to true in your nuxt.config.js file.

Upvotes: 1

Related Questions