loading...

re: When Why and How to use Vuex VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Thanks for this article! My (probably stupid) question is how would you use VueX to connect and manipulate an external data source? Thanks again!
 

I'm hoping that your question was resolved, but just in case:

You would use axios in your store to go and get data from the API. For example:

import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import VueAxios from "vue-axios";

Vue.use(Vuex);
Vue.use(VueAxios, axios);

export default new Vuex.Store({
  state: {
    users: [],    
  },
actions: {
    loadUsers({commit}) {
      Vue.axios.defaults.baseURL = "https://jsonplaceholder.typicode.com/";
      Vue.axios.get('users').then(result => {
        commit('SAVE_USERS', result.data);
      }).catch(error => {
        throw new Error(`API ${error}`);
      });
    },
  mutations: {
    SAVE_USERS(state, users) {
      state.users = users;
    }
  }
})
 

I know we can do this without Vuex as well. Is there a scenario where one would need Vuex for this? I can see how using an action would make it easy to post and get data from a data source. Are there any other scenarios?

I agree with you here. When using Vuex it is supposed to manage a state that passes across multiple components. Dropping Axios into the store to make API calls works but is it really necessary?

I am just getting into Vue, like you, so not sure if my opinion comes with any value. However, with my experience, I prefer to keep things in the "separation of concern". I have created an HTTP Service that serves as the base HTTP Model where I add headers, base routes, etc. and any customization to the route I override the base for the route in use.

Again this route seems like it has value with Users, but I think it should be more clear on the example. What if you're getting something unique to a single component? You're not going to want or need to drop that into the store. I am also very hesitant to mutate the state within the store. Seems like it goes against the principle of the store. The state is a snapshot in time when would you need to manipulate that?

Code of Conduct Report abuse