source

Vuex - mapState 데이터로 작업하기 전에 API 호출과 초기 저장소를 기다립니다.

goodcode 2022. 8. 30. 22:12
반응형

Vuex - mapState 데이터로 작업하기 전에 API 호출과 초기 저장소를 기다립니다.

스토어 오브젝트로 작업을 수행하기 전에 느린 API 호출이 완료되고 저장을 커밋할 때까지 어떻게 기다리거나 기다려야 합니까?

예를 들어,created()App.js에서는 다음 작업을 수행하는데, 변환 함수를 타임아웃 내에 정리하지 않으면 데이터가 아직 커밋되지 않아 실패합니다.

App.js

created: function () {
    this.$store.dispatch("loadData"); // loads all the data and commits to store as state.eventsData

    setTimeout(() => { // if I don't wrap these in a timeout, this.eventsData is not available for the functions
      this.transformDataForGrid(); // transforms eventsData and commits it as gridData
      this.transformDataForCalendar(); // transforms eventsData and commits it as calendarData
    }, 500);
  },
methods: {
  transformDataForGrid(){// lots of manipulations of eventsData then state.commit("gridData", newdata},
  transformDataForCalendar(){},// lots of manipulations of eventsData then state.commit("calendarData", newdata},
}

내가 알아냈어Boolean 스토어 아이템을 만들었습니다.loading처음에 true로 초기화했습니다(페이지 로드).또한 변이가 생겼고setLoading. App.vue에서created(){}액티오스 API 호출을 위한 액션을 디스패치합니다.에서.then그 중 데이터를 스토어에 커밋하고 set Loading도 false로 커밋합니다.그런 다음 App.vue I mapState로 돌아갑니다.loading로딩이 바뀌면 트랜스포메이션 기능을 해제할 수 있도록 "관찰"합니다.

앱.

  computed: mapState(["loading", "eventsData"]),
  watch: {
    loading() {
      if (!this.loading) { // when loading changes to false in store/index.js I fire off my functions
        this.transformDataForGrid();
        this.transformDataForCalendar();
      }
    },
  },
  created: function () {
    this.$store.dispatch("loadData"); // load data
  },
methods: { 
  transformDataForGrid(){ // do stuff },
  transformDataForCalendar() { // do other stuff },

}

store/index.displaces

  mutations: {
    ... // other mutations
    setLoading(state, loading) {
      state.loading = loading;
    },
  },
  actions: {
    loadData({ commit }) {
      axios
        .get("/data/eventsData.json")
        .then((response) => {
          commit("setEventsData", response.data);
          commit("setGridData", response.data);
          commit("setCalendarData", response.data);
          commit("setLoading", false); // loading is done
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },

언급URL : https://stackoverflow.com/questions/62808461/vuex-wait-for-api-call-and-initial-store-before-working-with-mapstate-data

반응형