Vuex: Axios GET 요청에서 구성 요소 내부에 정의되지 않은 값이 반환됨
API에 GET 요청을 하기 위해 Vuex/Axios를 사용하고 있습니다.컴포넌트가 마운트되면 Vuex 스토어에 액션을 디스패치하여 Axios GET 요청을 합니다.Vuex 작업에서 Axios GET 요청은 예상대로 응답을 반환하지만 구성 요소 내부의 응답은 정의되지 않은 상태로 반환됩니다.내가 뭘 잘못하고 있지?
axios/index.js
import axios from 'axios';
const API_URL = 'http://localhost:3000/api/v1/';
const plainAxiosInstance = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
});
export { plainAxiosInstance };
Vuex 모듈:store/modules/character.js
이 파일에서는response
는 올바른 응답을 기록합니다.그fetchCharacters
이벤트가 컴포넌트에서 트리거됩니다.
import { plainAxiosInstance } from '@/axios';
const characterModule = {
namespaced: true,
state: {
characters: []
},
mutations: {
SET_CHARACTERS(state, characters) {
state.characters = characters;
}
},
actions: {
async fetchCharacters({ commit }) {
await plainAxiosInstance
.get('/characters')
.then(response => {
let characters = response.data;
commit('SET_CHARACTERS', characters);
console.log(characters); <-- Logs the expected response data
return characters;
})
.catch(error => console.log('Failed to fetch characters', error));
}
},
getters: {}
};
export default characterModule;
그런 다음 마운트 상의 Vue 컴포넌트 내부에 Vuex 액션을 디스패치합니다.
<script>
import { mapState, mapActions } from 'vuex';
export default {
mounted() {
this.fetchCharacters()
.then(response => {
console.log('response', response);
// response is logging undefined here <----
})
.catch(error => {
console.log(error);
});
},
computed: mapState(['character']),
methods: mapActions('character', ['fetchCharacters'])
};
</script>
console. 로그인modules/character.js
는 예상대로 데이터를 기록하고 다음으로 컴포넌트 로그 내의 응답이 정의되지 않았습니다.변수를 돌려보내고characters
Vuex 모듈로 이동합니다.그리고 Vuex 액션도 만들었습니다.fetchCharacters
비동기입니다.그럼 왜 컴포넌트 내의 응답이 정의되어 있지 않은 것일까요?
도와주시면 고맙겠습니다.
변경:
async fetchCharacters({ commit }) {
await plainAxiosInstance
다음과 같이 입력합니다.
fetchCharacters({ commit }) {
return plainAxiosInstance
보관해 둘 수 있습니다.async
당신이 원한다면, 하지만 별반 다를 게다.
현재의 형태에서는, 그 액션은 암묵적으로 약속을 반환하고, 그 약속은 요구가 완료될 때까지 해결되지 않습니다.그러나 이 약속을 원하는 값으로 해결하기 위해 할 말은 없습니다.
행동 속에서 약속을 기다리는 대신 대신 그 약속을 돌려줄 수 있습니다.외부적으로는 어느 쪽이든 약속을 돌려받을 수 있기 때문에 차이가 없지만 요청이 완료되면 그 약속은 올바른 값으로 해결됩니다.
언급URL : https://stackoverflow.com/questions/58742190/vuex-axios-get-request-returns-undefined-inside-component
'itsource' 카테고리의 다른 글
신뢰 저장소 vs 키 저장소 - 키 도구를 사용하여 생성 (0) | 2022.08.17 |
---|---|
Vue2: 메모리 리크 (0) | 2022.08.17 |
자바에서는 어레이 내의 모든 숫자의 합계를 어떻게 찾을 수 있습니까? (0) | 2022.08.17 |
요소 UI의 입력 구성 요소와 $ref 사용 (0) | 2022.08.17 |
C에서 빅 엔디안을 리틀 엔디안으로 변환하다[제공된 펑크를 사용하지 않고] (0) | 2022.08.17 |