source

SSR 사용 시 Nuxt Store의 초기 상태가 정의되지 않았습니다.

goodcode 2022. 8. 3. 23:13
반응형

SSR 사용 시 Nuxt Store의 초기 상태가 정의되지 않았습니다.

상태를 초기화하고 API에서 데이터를 가져와 상태를 변환하기 위해 인덱스 페이지에 Nuxt 스토어를 만들었습니다.

초기 상태, 돌연변이, 행동을 포함한 제 스토어 코드입니다.

import Axios from "axios";

//a controller has a store that it interfaces with

// set initial state of the store
const initState = () => ({
  message: "init"
})

// make the state usable from other components
export const state = initState

//when you need to change the state
//for mutations you do commits
export const mutations = {
  setMessage(state, message) {
    state.message = message
  }, //can define more functions here
  reset(state) {
    Object.assign(state, initState())
  }
}

//when you have to do API calls (async)
//commit parameter allows us to invoke the mutation functions
//for actions you do dispatch
export const actions = {
    async nuxtServerInit({commit}) {
      const message = await Axios.get("http://localhost:5000/api/home").data;
      console.log(message);
      commit("setMessage", message) //put name of mutation as parameter + payload
    }
}

내 index.vue 파일에서 필요한 기능을 vuex에서 가져오고 상태를 매핑합니다.

import Logo from '~/components/Logo.vue'
import VuetifyLogo from '~/components/VuetifyLogo.vue'
import Axios from "axios";
import {mapState, mapActions, mapMutations} from 'vuex'

export default {
  components: {
    Logo,
    VuetifyLogo
  },
  computed: mapState({
    message: state => state.message
  }),
  methods: mapMutations([
    "reset",
    "setMessage"
  ])

그러나 (Vue 개발 도구를 사용하여) 페이지를 로드하면 상태가 정의되지 않기 시작합니다."reset" 메서드를 통해 상태를 변환할 수 있지만 데이터를 가져오기 위해 API가 호출되지 않습니다.콘솔에 오류가 표시되지 않기 때문에 원인이 무엇인지 알 수 없습니다.API도 가동되고 있습니다.

페이지를 로드할 때 nuxtServerInit 액션이 호출되도록 하려면 어떻게 해야 합니까?

제 생각에는nuxtServerInit액션이 올바르게 호출됩니다.장담하건대message값은 항상 정의되어 있지 않습니다.왜냐하면Axios.get("http://localhost:5000/api/home")Atribute 데이터가 없는 약속을 반환합니다.먼저 결과를 기다렸다가 데이터를 얻어야 합니다.

// note extra parentheses
const message = await (Axios.get("http://localhost:5000/api/home")).data;

또한 Axios 콜을 try-catch로 래핑할 수도 있습니다.그렇지 않으면 콜이 실패했을 경우 스택트레이스를 포함한 기본 Nuxt 오류 페이지가 나타납니다.

  async nuxtServerInit ({ commit }: any) {
    try {
      const message = (await Axios.get('http://localhost:5000/api/home')).data;
      console.log(message);
      commit('setMessage', message); // put name of mutation as parameter + payload
    } catch (error) {
      // you could redirect to custom error page for instance
      console.error(error);
    }
  }

언급URL : https://stackoverflow.com/questions/64184340/initial-state-from-nuxt-store-is-undefined-when-using-ssr

반응형