Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from vuex state into local data for manipulation

I'm having trouble understanding how to interact with my local state from my vuex state. I have an array with multiple items inside of it that is stored in vuex state. I'm trying to get that data from my vuex state into my components local state. I have no problems fetching the data with a getter and computed property but I cannot get the same data from the computed property into local state to manipulate it. My end goal is to build pagination on this component.

I can get the data using a getters and computed properties. I feel like I should be using a lifecycle hook somewhere.

Retrieving Data

App.vue:

I'm attempting to pull the data before any components load. This seems to have no effect versus having a created lifecycle hook on the component itself.

export default {
  name: "App",
  components: {},
  data() {
    return {
      //
    };
  },
  mounted() {
    this.$store.dispatch("retrieveSnippets");
  }
};

State:

This is a module store/modules/snippets.js

const state = {
   snippets: []
}

const mutations = {
SET_SNIPPETS(state, payload) {
    state.snippets = payload;
  },
}

const actions = {
retrieveSnippets(context) {
    const userId = firebase.auth().currentUser.uid;
    db.collection("projects")
      .where("person", "==", userId)
      .orderBy("title", "desc")
      .onSnapshot(snap => {
        let tempSnippets = [];
        snap.forEach(doc => {
          tempSnippets.push({
            id: doc.id,
            title: doc.data().title,
            description: doc.data().description,
            code: doc.data().code,
            person: doc.data().person
          });
        });
        context.commit("SET_SNIPPETS", tempSnippets);
      });
  }
}

const getters = {
  getCurrentSnippet(state) {
    return state.snippet;
},

Inside Component

data() {
    return {
      visibleSnippets: [],
   }
}
computed: {
stateSnippets() {
      return this.$store.getters.allSnippets;
    }
}

HTML:

you can see that i'm looping through the array that is returned by stateSnippets in my html because the computed property is bound. If i remove this and try to loop through my local state, the computed property doesn't work anymore.

<v-flex xs4 md4 lg4>
  <v-card v-for="snippet in stateSnippets" :key="snippet.id">
    <v-card-title v-on:click="snippetDetail(snippet)">{{ snippet.title }}</v-card-title>
  </v-card>
</v-flex>

My goal would be to get the array that is returned from stateSnippets into the local data property of visibleSnippets. This would allow me to build pagination and manipulate this potentially very long array into something shorter.

like image 429
Kris Tryber Avatar asked Jul 18 '19 13:07

Kris Tryber


People also ask

Where is Vuex data stored?

In Vuex, our data store is defined as state in the store/index. js config object. Even though it sounds like new terminology to learn, think of it as the data property that we have been using this whole time.

What is the use of mapState in Vuex?

Mapping State Vuex provides a helper function called mapState to solve this problem. It is used for mapping state properties in the store to computed properties in our components. The mapState helper function returns an object which contains the state in the store.

What is mapState?

mapState is a helper that simplifies creating a computed property that reflects the value of a given state. Similarly: mapGetters is a helper that simplifies creating a computed property that reflects the value returned by a given getter. Note that even method-style getters should be mapped to computed properties.


1 Answers

You can get the state into your template in many ways, and all will be reactive.

Directly In Template

<div>{{$store.state.myValue}}</div>
<div v-html='$store.state.myValue'></div>

Using computed

<div>{{myValue}}</div>
computed: {
  myValue() { return this.$store.state.myValue }
}

Using the Vuex mapState helper

<div>{{myValue}}</div>
computed: {
  ...mapState(['myValue'])
}

You can also use getters instead of accessing the state directly.

The de-facto approach is to use mapGetters and mapState, and then access the Vuex data using the local component.

Using Composition API

<div>{{myValue}}</div>
setup() {
 // You can also get state directly instead of relying on instance.
 const currentInstance = getCurrentInstance()
 const myValue = computed(()=>{
   // Access state directly or use getter
   return currentInstance.proxy.$store.state.myValue
 }) 
 return {
  myValue
 }
}
like image 51
Steven Spungin Avatar answered Oct 06 '22 23:10

Steven Spungin