0

I need to get remote data to be displayed in every pages.

This call is perfomed in store/index.js:

export const state = () => ({
  contact: {
    hello: "World"
  }
});

export const actions = {
  async nuxtServerInit({ commit, state }) {
    const { contactData } = await this.$axios.get("/contact");
    commit("SET_CONTACT", contactData);
  }
};

export const mutations = {
  SET_CONTACT(state, contactData) {
    state.contact = contactData;
  }
};

Problem is that the value of contact turns to undefined in the store, whereas expected content is retrieved through Axios (the retrieved content is displayed in the SSR console...)

What am I missing here?

Yako
  • 3,405
  • 9
  • 41
  • 71
  • Usually, the response of an axios request contains a key called `data`, which holds whatever the endpoint returned. Line 8 of your code tries to deconstruct the response directly, it should therefore be something like `this.$axios.get("...").data;` - see https://github.com/axios/axios#response-schema – thormeier Sep 25 '19 at 16:58
  • I'm not really sure. Doing so, I'll get this error: `Cannot destructure property 'contactData' of 'undefined' or 'null'.`. I suppose that Nuxt Axios already presents the `data` content: https://axios.nuxtjs.org/usage – Yako Sep 29 '19 at 15:01

1 Answers1

0
export const actions = {
  async nuxtServerInit({ commit, state }, {app} ) {
    const { contactData } = await app.$axios.get("/contact");
    commit("SET_CONTACT", contactData);
  }
};
Vimbi
  • 66
  • 1
  • 5
  • 1
    When your code is nearly identical to the block in the question, please add an explanation. – General Grievance Aug 18 '22 at 12:26
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. – jasie Aug 18 '22 at 12:34