Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt.js fetch on page reload

When using nuxt.js fetch(), whenever I reload the page, it does not fetch it again. Only if I come from a router-link. How do I force it to actually refetch from my API?

export default {
    async fetch() {
        const data = await this.$axios.$get(`/users/${this.$route.params.name}`)
        this.user = data
    },
    data() {
        return {
            user: []
        }
    }
}

Every page I look at, they always show placeholders on page refresh, WHILE refetching from their APIs, why does my Nuxt.js app not do that when refreshing? It is just not refetching the data from my API, which is weird.

like image 249
CunnertA Avatar asked Aug 25 '20 21:08

CunnertA


2 Answers

Just ran into the same issue.

After browsing the options section of the Nuxt docs on fetch, it looks like setting the fetchOnServer option to false triggers the fetch hook on both the client-side and when the page reloads (server side), solving the issue:

fetchOnServer: false
like image 116
Tom Ray Avatar answered Sep 28 '22 06:09

Tom Ray


I believe, in Nuxt.JS, the fetch method is only called on rendering from router navigation - a manual reload would not trigger this.

Perhaps you could construct a mixin using beforeMount() instead of fetch() and apply this to the pages where this was required.

Or of course, just on the page itself:

async beforeMount() {
    const data = await this.$axios.$get(`/users/${this.$route.params.name}`)
    this.user = data
},

https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12/

like image 25
Jordan Avatar answered Sep 28 '22 06:09

Jordan