Search code examples
vue.jsvuexstore

How to set up store date


I have data I would like to use in multiple components and manipulate. For that reason I decided to start using store, but I don't know at what stage I'm supposed to do request to the server and set store data.

The question is probably asked before but I could not find it


Solution

  • Your question is not clearly but if you want to centralize your logic. Your store file looks like that:

    state:{
       user:{
          id: "",
          name: "",
          ...
          ..
          .
       }
    }
    
    getters:{
       get_user: state => state.user,
       get_userID: state => state.user.id,
       ...
    }
    
    mutations:{
       SET_USER(state, payload){
          state.user = payload
       },
       SET_USER_ID(state, payload){
          state.user.id = payload
       }
       ...
    }
    
    actions:{
       add_user({ commit }, userData){
          // you can make some http request here if you have
          commit("SET_USER", userData)
       }
    }
    

    Basically, above code is showing you a logic. If you want to get some data which is in state, you should had a getters. If you want to change some data which is in state, you should use mutations to make this. If you want to make some functionality like post user detail to server, fetching data from server something like this you should use actions and even you can make those changes in your actions, don't. Because actions work async, mutations not.

    I hope this is answer what you looking for.