Search code examples
nuxt.jsvuexnuxtjs2

NuxtJS computed property running only on navigate


component

<script>
import { mapState } from 'vuex';

export default {
    
    layout: 'index',

    /**
     * Run State Dispatches
     */
    async fetch({store}) {
        store.dispatch('api/contracts/all')
    },
    /**
     * Create State Mapping
     */
    computed: {
        ...mapState({
            contracts: 'contracts'
        })
    }    
}
</script>

api/contracts

const axios = require("axios");

export const state = () => ({
  contracts: [],
})

export const mutations = {
  SET_CONTRACTS (state, contracts) {
    state.contracts = contracts
  }
}

export const actions = {
  async all({ commit }) {
    let response = await getApi(`/api/products`, this.$axios)
    let contracts = response.data

    commit('SET_CONTRACTS', contracts);
  }
}

const getApi = async function (url, axios) {
  let response = await axios.get(url)

  return {
    data: response.data
  }
}

I am having some issues with the above, if I refresh the page, the contract request isn't seen in network tab, however, if I navigate inside the application, to another page, and return, the contract request is there in network, why is this happening, the contract request should load when the page loads?

To be clear, if I navigate to another page via a NuxtLink(without refreshing), and return the contract request is visible in network tab, and works - if I refresh the page, the contract request isn't ran!


Solution

  • NuxtJS supports SSR (server side rendering) which means that :

    • If you are at the first loading of the page or you refresh the page, your request will be executed from the server side and that's why you don't see it in the network tab.
    • If you try to navigate to your page from another page without refreshing it you will be redirected only from the client side and in this case you can see your request in the Network tab.

    For more info check : https://nuxtjs.org/docs/features/rendering-modes You can set the'fetchOnServer' property to false in your component to disable fetching page from the server side.