programing

Vuex 액션 - Axios 반환 약속

goodsources 2023. 2. 6. 23:27
반응형

Vuex 액션 - Axios 반환 약속

공리들이 돌려준 약속을 두 곳에서 사용하는 데 어려움이 있다.사용하고 싶다.then()Vuex 액션의 내면에 있는 내 상태에 변경을 커밋하고, 공리적인 약속을 반환하고, 그것을 사용한다..then()UI를 업데이트하기 위해 컴포넌트 내에서 다시 작업을 수행합니다.제가 직면한 문제는 약속 응답이 컴포넌트 내부에서 정의되어 있지 않다는 것입니다.

// component
methods: {
  getUser(userId) {
    this.$store.dispatch('GET_USER', userId)
      .then(response => {
        console.log(response); // undefined
      });
  }
}

// vuex
actions: {
  GET_USER: ({commit}, userId) => {
    return api.getUserById(userId)
      .then(({data}) => {
        commit('ADD_USER', data);
      });
  }
}

// api service
getUserById(userId) {
  return axios.get('/api/users/' + userId);
}

의 사용을 삭제하면.then()내 Vuex 액션 안에responseapi에서 오브젝트가 되지만 컴포넌트에 약속을 해서catch에러입니다.

// component
methods: {
  getUser(userId) {
    this.$store.dispatch('GET_USER', userId)
      .then(response => {
        console.log(response); // no longer undefined
      });
  }
}

// vuex
actions: {
  GET_USER: ({commit}, userId) => {
    return api.getUserById(userId); // removed 'then' method
  }
}

첫 번째 코드 블록의 문제점은 무엇입니까?
감사해요.

첫 번째 블록에서는then아무것도 반환하지 않습니다.따라서 반환됩니다.undefined해결된 값을 반환하면 이 문제가 해결됩니다.

검색, mapGetters, mapActions 및 비동기 함수를 체크해야 합니다.

예를들면

api에 요청하시면 가능합니다.

//api.js

import axios from 'axios'
export aync function getuser() {
  ... 
  ...
  const data = await axios.get(url,{params:{....}})
  return data
}
//component
import {getuser} from '@/app.js'
import {mapAction} from 'vuex'
  data() {
  return {
    data:null
  }
}
methods: {
..mapAction('getUserAction')
  async getUserMethod () {
    this.data = await getuser()
    this.getUserAction(this.data)
  }
}



//store.js
actions: {

getUserAction () {
  // your actions..
  }
}

언급URL : https://stackoverflow.com/questions/53649336/vuex-action-returning-axios-promise

반응형