Search code examples
vuejs2vuexnuxt.jsprefetch

Pre-fetch api data in Vuex with Nuxt.js


I am trying to pre-fetch some data and update Vuex before client-side kicks in.

store/index.js

export const state = () => ({});
export const getters = {};
export const actions = {
  async nuxtServerInit ({ dispatch }) {
    await dispatch('nasa/getImages');
  }
};

store/moduleName.js

import fetch from 'node-fetch';

export const state = () => ({
  images: []
});

export const mutations = {
  storeImages(state, data) {
    state.images = [];
    state.images.push(...data);
    console.log(state.images[0]); <- this logs in the terminal
  }
}

export const actions = {
  getImages(store) {
    return fetch('api/url').then(response => {
      response.json().then(function(data) {
          store.commit('storeImages', data.collection.items.slice(0, 24));
      });
    });
  }
}

My mutation gets triggered by nuxtServerInit and I am getting the first element logged in the terminal on page load. My store in the client-side however, is empty.

What am I missing?


Solution

  • With help from a friend we have managed to fix this issue by removing node-fetch and adding axios to Vuex instead.

    The only change made was in store/moduleName.js which now looks like:

    import Axios from 'axios'
    
    export const state = () => ({
      images: []
    });
    
    export const mutations = {
      storeImages(state, data) {
        state.images.push(...data);
      }
    }
    
    export const actions = { 
      async getImages(store) {
        let res = await Axios.get('api/url');
        store.commit('storeImages', res.data.collection.items.slice(0, 24));
      } 
    }