itsource

Vuex: Axios GET 요청에서 구성 요소 내부에 정의되지 않은 값이 반환됨

mycopycode 2022. 8. 17. 23:57
반응형

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는 예상대로 데이터를 기록하고 다음으로 컴포넌트 로그 내의 응답이 정의되지 않았습니다.변수를 돌려보내고charactersVuex 모듈로 이동합니다.그리고 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

반응형