asyncData hook when hard refreshing in Nuxt

809 views Asked by At

I just realized that the asyncData hook is not called when hard refreshing the page. But I have important data to load to show on that page. And I want to make sure that they are always available, even when the user hard refreshes the page.

1

There are 1 answers

0
kissu On

asyncData from the documentation

the promise returned by the asyncData hook is resolved during route transition

In that case, the best way is to use the fetch() hook and display a loader while you do finish your calls thanks to the $fetchState.pending helper.

Actually, I do think that fetch() is better in many ways.

Quick article on the subject: https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12/
The one on the bottom of the page (Sergey's) is cool with some practical example of a nice implementation too.


You could also use this somewhat hacky solution in a layout to see if the initial location (the one you are when you hard refresh) is the one you want to be. Basically, if you land on a specific page (hard refresh or following a new window page for example) but want to have some custom behavior.

beforeCreate() {
  if (!['some-other-page'].includes(this.$router.history._startLocation)) {
    this.$router.replace({ name: 'index' }).catch(() => {})
  }
},

Still, this one infinite loops if used in a middleware (or I made a mistake) and it's less clean than a fetch() hook.