Reputation: 13
I've a doubt..
In my Nuxt static project pages (Nuxt version => 2.12), I need to be fast with data recuperation.
With asyncData, the objective of speed is checked, because with asyncData I can get data during the component render. But this project has 3 different possible API calls, as many as the languages that I set and, when I select one language the value is saved in the Vuex store.
At the same time of this process, the language value is also saved on local storage, so, if I use only asyncData, when the page is refreshed the API call will not be the right call with the saved language (asyncData can't access the local storage).
Here, the fetch hook enters into the game, with the watch set on the state language value of the store, it can trigger the fetch and get the right data. Moreover, even when the page is refreshed, the fetch hook, being able to read the values of the local storage, can do its work great.
So why don't I use only the fetch hook? Because the fetch is slower than asyncData.
Is the use of both fetch and asyncData an anti-pattern?
Is there a better way?
Here my code:
export default {
asyncData (context) {
const slug = (context.route.path === '/' || context.route.path === '') ? '/home' : context.route.path
return context.app.$storyapi
.get(`cdn/stories${slug}`, {
language: context.store.state.language.language
}).then((res) => {
return res.data
}).catch((res) => {
context.$errorMessage(res.response,
'Sorry but this content doesn\'t extist', `Sorry, but the content called: "${context.route.name}" has a problem or doesn't exist`
)
})
},
data () {
return {
story: {
content: {}
}
}
},
async fetch () {
const slug = (this.$route.path === '/' || this.$route.path === '') ? '/home' : this.$route.path
const { data } = await this.$storyapi.get(`cdn/stories${slug}`, {
language: this.$store.state.language.language
})
this.story = data.story
},
watch: {
'$store.state.language.language': '$fetch'
}
}
Just to complete the information I would like to further say that the code works well, the matter is concerning the best practice.
Upvotes: 1
Views: 1239
Reputation: 46612
Since when fetch()
is slower than asyncData()
?
Also, if you really need to re-run something you can totally use await this.$nuxt.refresh()
.
You could probably run both of those but they can kinda make the same thing, so it's kinda a duplication and I'd recommend to choose only one.
I'm not sure how it being located in localStorage is an issue but you could probably use one of the available packages to have an universal storage of this data, like this one: https://github.com/unjs/unstorage
If not, cookies should be enough too (available both on server and client).
Upvotes: 1