I'm building a website with Nuxt.js 2 with static site generation (npm run generate).
I receive the data in my asyncData function and use it to generate the page.
nuxt.config.js
generate: {
routes(){
console.log("generate")
let recettes = axios({
url: process.env.GRAPHQL_ENDPOINT,
method: "post",
data: {
query: queries.generateRecipes(),
}
}).then((result) => {
return result.data.data.recettes.map(recette => {
console.log(recette)
return {
route: `Recette/${recette.slug}/${recette.recipeId}`,
payload: recette
}
})
});
return Promise.all([recettes]).then((values) => {
console.log(values);
return values[0];
});
},
fallback: '404.html'
}
Recette\_slug\_id.vue
async asyncData({ params, error, payload, $axios, $config: { graphqlEndpoint } }){
console.log("params",params)
if (payload){
console.log("payload",payload.name);
let recipe = payload;
if(recipe.compositions){
recipe.compositions.sort((a,b) => b.quantity - a.quantity);
}
return { recipe: recipe, servings:recipe.yield };
}
else {
if(params.id){
console.log("fetchRecipe", params.id);
const res = await $axios({
url: graphqlEndpoint,
method: "post",
data: {
query: queries.getRecipeDetails(params.id),
},
})
if(res.data.data && res.data.data.recettes[0]){
let recipe = res.data.data && res.data.data.recettes[0];
if(recipe.compositions){
recipe.compositions.sort((a,b) => b.quantity - a.quantity);
}
return { recipe: recipe, servings:recipe.yield};
}
else{
error({ statusCode: 404, message: 'Page not found' })
}
}
error({ statusCode: 404, message: 'Page not found' })
}
}
It is correctly generated and the payload.js file too. The payload.js is loaded by the browser when the page is loaded.
However, when my object is called client-side it fails because it's undefined. I get the following error: TypeError: this.recipe is undefined
I can't figure out why is undefined. In the created() hook I made a console log of this._data and indeed, my recipe object isn't there
created(){
console.log(this._data);
console.log(this.dummy);
console.log(this.recipe);
}
My problem is similar to this one: Nuxt js full static dynamic page, payload undefined but no solution is provided
Source code is here: https://github.com/nbwns/fristouille