A
A
Artem Kondratsky2020-02-05 21:36:06
WordPress
Artem Kondratsky, 2020-02-05 21:36:06

Why is axios nuxt not sending request?

Hello, there is a problem with getting data through the axios module for nuxt. The request is simply not sent.

store/portfolio.js

export const state = () => ({
  portfolio: []
})

export const mutations = {
  updatePortfolio (state, items) {
    state.portfolio = items
  }
}

export const actions = {
  async fetchPortfolio ({ commit }) {
    const portfolio = await this.$axios.$get('http://localhost:8081/portfolio')
    commit('updatePortfolio', portfolio)
  }
}

export const getters = {
  portfolio: s => s.portfolio
}



components/Wall.vue

import Item from '~/components/Portfolio/Item.vue'

export default {
  name: 'PortfolioWall',
  components: {
    Item
  },
  computed: {
    portfolio () {
      return this.$store.getters['portfolio/portfolio']
    }
  },
  async fetch ({ store }) {
    if (store.getters['portfolio/portfolio'].lenght === 0) {
      await store.dispatch('portfolio/fetchPortfolio')
    }
  }
}



No errors are displayed in the console.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2020-02-05
@kondrackii

It's hard to give a definitive answer without seeing the full picture.
But the fetch method seems to work only for page components. And as far as I understand, this is not the case.

A
Alexs7, 2020-12-29
@Alexs7

I also encountered such a problem, as a result, I solved it like this:
from nuxtServerInit I took out all the asynchronism into a separate action

async nuxtServerInit({dispatch}) {
        await dispatch('loadInitialPosts')
},

And after that, in those components that did not render asynchronous data from the store. Now I just pull this action (loadInitialPosts), the posts are loaded into the store, and I insert this data through computed into the markup of the component and the posts appear.
This is how the component looks like, checking if, so as not to pull the server once again
created() {
        if (!this.getPostsLoaded || this.getPostsLoaded.length === 0) {
             // Если стор пустой
            this.$store.dispatch('loadInitialPosts')
        }
    },
computed: {
    getPostsLoaded() {
        return this.$store.getters.getPostsLoaded
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question