Short disclaimer at the beginning - this one might be not valid anymore soon because the Nuxt 3.0 is just right behind the corner. Along with it, we will get a new, fresh, and shiny useFetch
API. Recreated with Composition API it will change the whole process of fetching data across our Nuxt apps.
A simple example will look like:
import { useFetch } from '@nuxt/composables'
export default {
async setup() {
const { data: posts } = await useFetch('https://your.api.url')
return posts
}
}
Sexy, I know. π
But since it's not public and not quite official at that very moment we still using the 2.x
version of the framework and we still lay our apps on the existing API. According to that, this might be helpful for some of you.
As we all know for various cases of data fetching we can use the fetch()
hook with $fetchState
object which contains pending
and error
values. It also can be recalled with this.$fetch
method. For others when we need our data just before the page render we have to use asyncData
. One problem with asyncData
is that we can't call it again - for example on route change action. What we can do about it then?
Firstly define your fetch
function outside the regular component.
async fetch() {
const { posts } = await forApiResponse()
return {
posts
}
}
Then inside the asyncData
hook use this function.
asyncData() {
return fetch()
}
Recall it while watching some route changes.
data: () => ({
posts: []
}),
watch: {
$route() {
const data = fetch()
Object.assign(this.$data, data)
}
}
To avoid data conflicts we might want to reset it to the default state before fetching it again. Maybe this one is not so elegant as the fancy fetch()
API but that way we can get our data before the page renders and react to it. Displaying a 404 error for example - very valuable from SEO perspective.
And this is it. Enjoy.
Top comments (0)