[Vuejs]-What is the difference between using promises with and without return

0👍

a promise doesn’t work as a simple declaration inside a function, you have actually return the promise to work with it. The case here is a little bit weird tho, becuase axios already returns a promise to work with. I think the problem is that you want to assing the value of a variable in the state of the store programatically to a variable in component data, when the correct flow for something like that would be accessing that value with a computed property, like this:

Vuex

import Vue from "vue";
import Vuex from "vuex";
import axios from 'axios';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    news: []
  },
  getters:{
    getNews(state){
      return state.news
    }
  },
  mutations: {
    UPDATE_NEWS(state, payload){
      state.news = payload
    }
  },
  actions: {
    updateNews(context){
      var url = 'https://newsapi.org/v2/top-headlines?' +
      'country=us&' +
      'apiKey=something';
      axios
        .get(url)
        .then(response => {
          context.commit('UPDATE_NEWS', response.data)
        })
        .catch( error => console.log('Oops, something went wrong with the news', error) );
    }
  },

});

Component

created () {
  this.$store.dispatch('updateNews');
},
computed: {
  news() {
    return this.$store.getters.getNews;
  }
}

Using it like this, you don’t have to make a variable called news inside component’s data, just the computed property, and access it the same way you would access a variable returned in component’s data

Leave a comment