Reputation: 65
Edit: I can't get the params.id because nuxt-link pass it to detail page.
I'm trying to build a blog with NuxtJS.
This is the link for blog detail page.
<nuxt-link :to="{name: 'category-slug', params: { slug: slug, id: id, category: category } }">
It works well but after I refresh detail page (i.e: tech/hello-world), it returns Cannot read property 'author' of null
_slug.vue
<template>
<div>
<h1>slug {{ $route.params.id }}</h1>
{{ loadedPost.author }}
</div>
</template>
<script>
import Vuex from "vuex"
import axios from "axios"
export default {
asyncData(context) {
console.log(context.params.id)
return axios.get('https://howto-a9089.firebaseio.com/posts/' + context.params.id + '.json')
.then(res => {
return {
loadedPost: res.data
}
})
},
}
</script>
I think there's a problem with asyncdata. Why it happens?
Upvotes: 0
Views: 1548
Reputation: 65
Thanks for answers. Here's the solution. _slug.vue only gets params.id when user clicks the below button.
<nuxt-link :to="{name: 'category-slug', params: { slug: slug, id: id, category: category } }">
When user enters directly this url or refresh the page, there will be no params.id. So I needed to GET data by "slug".
Thanks to Firebase:
return axios.get('https://howto-a9089.firebaseio.com/posts.json?orderBy="slug"&equalTo=' + '"' + params.slug + '"' + '&print=pretty')
Result: I got SEO friendly url now. :) (i.e url.com/tech/hello-world)
Upvotes: 0
Reputation: 164729
As per the documentation, you should set a default value for loadedPost
so you don't get errors like this while the asynchronous data is loading
export default {
data() {
return { loadedPost: {} }
},
asyncData({ params }) {
return axios.get(`https://howto-a9089.firebaseio.com/posts/${params.id}.json`)
.then(res => ({
loadedPost: res.data
}))
}
}
Without this, loadedPost
is null when your template attempts to display loadedPost.author
and that's why you get that error.
Upvotes: 1