IT이야기

Vuex: REST API에 대한 약속 호출을 사용하여 비동기 작업 처리

cyworld 2022. 3. 29. 21:47
반응형

Vuex: REST API에 대한 약속 호출을 사용하여 비동기 작업 처리

구성 요소를 렌더링할 때 원격 API에서 항목 목록을 로드해야 하는 장난감 앱을 만들기 위해 TypeScript with Vue/Vuex를 사용한다.아래 작업에서 나는 라이브러리를 사용한다.axioshttp 요청을 할 경우, 약속으로 이를 반환한다.

const actions = {    
  getCurrentSession(context: Context) {
    return axios.get("http://localhost:3000/sessions/current")
      .then((res) => {
        commitSharedFiles(context, res.data.shared_files);
      })
      .catch((e: string) => {
        console.error(e);
      });
  }
};

// export action
export const dispatchGetSharedFiles = dispatch(actions.getCurrentSession);

// commit
export const commitSharedFiles = commit(mutations.setSharedFileList);

// mutations to the state tree
const mutations = {
  setSharedFileList(state: State, sharedFiles: StoreState.DirFile[]) {
    state.sharedFileList = sharedFiles;
  }
};

작업의 비동기적 특성 때문에 저장소/상태 트리에서 가져온 파일 목록을 검색하기 전에 약속을 해결해야 함:

// this is called in the mounted() life cycle method:
Store.dispatchGetSharedFiles(this.$store).then(res => {
            this.sharedFiles = Store.readSharedFilesList(this.$store);
});

이것은 효과가 있지만, 나는 그 약속을 해결한 다음 자료를 얻는 것이 매우 복잡하다고 생각한다.Vuex에서 비동기식 작업을 사용하는 더 나은 방법이 있는가? 고마워.

사용하다async/await작업 및 매핑용getter스토어에서 항목 검색(작업 맵도 표시)

// store.ts
const actions = {    
  async FetchSharedFiles(context: Context) {
    // omitted error handling for brevity
    let {res} = await axios.get("http://localhost:3000/sessions/current")
    commitSharedFiles(context, res.data.shared_files);
  }
};

// component.ts
import { mapGetters } from 'vuex'
...
mounted () {
  // again, do any necessary error handling
  this.$store.dispatch('FetchSharedFiles')
},
computed: {
  ...mapGetters({
    sharedFiles: 'namespace/getSharedFiles'
  })
}

이 패턴을 사용하면 vuex의 반응성이 이점을 얻을 수 있으므로sharedFiles작업이 완료되고 응답 데이터를 커밋할 때 구성 요소에서 업데이트를 트리거할 수 있음.그러면 템플릿이 다음과 같을 수 있음:

<template>
  <div v-for="(file, i) in sharedFiles" :key="i">
    // layout for each item...
  </div>
</template>

참조URL: https://stackoverflow.com/questions/49849725/vuex-handle-async-action-with-promise-call-to-rest-api

반응형