반응형
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 액션 안에response
api에서 오브젝트가 되지만 컴포넌트에 약속을 해서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
반응형
'programing' 카테고리의 다른 글
Vuetify 진행률 막대 계산에서 null 값을 제거하는 방법 (0) | 2023.02.06 |
---|---|
MySQL 오류: '사용자 'root'@'localhost'에 대한 액세스가 거부되었습니다. (0) | 2023.02.06 |
효과적인 최종 vs 최종 - 다른 동작 (0) | 2023.02.06 |
필요한 경우 소수점 이하 2자리까지 반올림하는 방법 (0) | 2023.02.06 |
복제 가능이 권장되지 않는 이유는 무엇입니까? (0) | 2023.02.06 |