0

I have a computed property that pulls some data out of my vuex store like so:

computed: {...mapGetters(["allCategories"])},

Each category in this.allCategories looks like so:

{ "id": "123", "name": "Foo" }

I want to pull out every name field from this.allCategories before the component is mounted in put each name into an reactive data property called categoryNames.

How can I achieve this?

What I have tried so far is below:

beforeMount() {
    for (let i = 0; i < this.allCategories.content.length; i++) {
      var name = this.allCategories.content[i].name
      this.categoryNames.push(name);
    }
},

Which gives the following error:

 Error in beforeMount hook: "TypeError: Cannot read property 'length' of undefined"

this.allCategories looks like so:

{
    "content": [
        {
            "id": "efb038df-4bc9-4e31-a37a-e805c9d7294e",
            "parentCategoryId": "8ffc214f-fff1-4433-aac9-34d13b4e06c5",
            "name": "Foo"
        },
        {
            "id": "5905d437-db2e-4f91-8172-c515577b86e9",
            "parentCategoryId": "5905d437-db2e-4f91-8172-c515577b86e9",
            "name": "Bar"
        },
        {
            "id": "8ffc214f-fff1-4433-aac9-34d13b4e06c5",
            "parentCategoryId": "8ffc214f-fff1-4433-aac9-34d13b4e06c5",
            "name": "Baz"
        }
    ],
    "number": 0,
    "size": 100,
    "total": 3
}

1 Answer 1

1

You could use the created hook to call a vuex action that calls a vuex mutation that grabs a state, do your parsing and store the parsed data in a new array in state, then use a getter to grab the parsed array from state.

created() {
    this.$store.dispatch('someAction');
},
computed: {
    ...mapGetters({
        parsedArray: 'getParsedArray',
    })
}
export const actions = {
    someAction({ commit }) {
        commit('SOME_MUTATION');
    },
}
export const mutations = {

  SOME_MUTATION(state) {
    let data = state.originalData;
     let parsedArray = [];

    // Do parsing work here

    state.parsedArray = parsedArray
  },

}
export const getters = {
  getParsedArray: state => {
    return state.parsedArray;
  },
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.