Vuex populate data from API call at the start

☆樱花仙子☆ 提交于 2020-07-23 06:20:48

问题


apologies for the simple question, I'm really new to Vue/Nuxt/Vuex.

I am currently having a vuex store, I wish to be able to populate the list with an API call at the beginning (so that I would be able to access it on all pages of my app directly from the store vs instantiating it within a component).

store.js

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

export const mutations = {
    set(state, testArray) {
        state.list = testArray
    }
}

export const getters = {
    getArray: state => {
        return state.list
    },
}

I essentially want to pre-populate state.list so that my components can call the data directly from vuex store. This would look something like that

db.collection("test").doc("test").get().then(doc=> {
    let data = doc.data();
    let array = data.array; // get array from API call
    setListAsArray(); // put the array result into the list
});

I am looking for where to put this code (I assume inside store.js) and how to go about chaining this with the export. Thanks a lot in advance and sorry if it's a simple question.

(Edit) Context: So why I am looking for this solution was because I used to commit the data (from the API call) to the store inside one of my Vue components - index.vue from my main page. This means that my data was initialized on this component, and if i go straight to another route, my data will not be available there.

This means: http://localhost:3000/ will have the data, if I routed to http://localhost:3000/test it will also have the data, BUT if i directly went straight to http://localhost:3000/test from a new window it will NOT have the data.

EDIT2:

Tried the suggestion with nuxtServerInit

Updated store.js

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

export const mutations = {
    set(state, dealArray) {
        state.list = dealArray
    }
}

export const getters = {
    allDeals: state => {
        return state.list
    },
}

export const actions = {
    async nuxtServerInit({ commit }, { req }) {
        // fetch your backend     
        const db = require("~/plugins/firebase.js").db;
        let doc = await db.collection("test").doc("test").get();
        let data = doc.data();
        console.log("deals_array: ", data.deals_array); // nothing logged
        commit('set', data.deals_array);       // doesn't work
        commit('deals/set', data.deals_array); // doesn't work
    }
}

Tried actions with nuxtServerInit, but when logging store in another component it is an empty array. I tried to log the store in another component (while trying to access it), I got the following:

store.state:  {                                                                                                                                     
  deals: {
    list: []
  }
}

回答1:


I would suggest to either:

  1. calling the fetch method in the default.vue layout or any page
  2. use the nuxtServerInit action inside the store directly

  1. fetch method

You can use the fetch method either in the default.vue layout where it is called every time for each page that is using the layout. Or define the fetch method on separate pages if you want to load specific data for individual pages.

<script>
export default {
  data () {
    return {}
  },
  async fetch ({store}) {
    // fetch your backend 
    var list = await $axios.get("http://localhost:8000/list");

    store.commit("set", list);
  },
}
</script>

You can read more regarding the fetch method in the nuxtjs docs here

  1. use the nuxtServerInit action inside the store directly

In your store.js add a new action:

import axios from 'axios';

actions: {
  nuxtServerInit ({ commit }, { req }) {
     // fetch your backend     
     var list = await axios.get("http://localhost:8000/list");

      commit('set', list);
    }
  }
}

You can read more regarding the fetch method in the nuxtjs docs here

Hope this helps :)



来源:https://stackoverflow.com/questions/62832863/vuex-populate-data-from-api-call-at-the-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!