The problem:
I'm creating a component in my nuxt/vue app. In my vuex store i fetch data ("allHandhelds") from an API and add it to an array. In my component I have a method that is supposed to find some data by index. When I display "allHandhelds" everything works fine. but when I add:
".findIndex((el) => el === "Form Factor");
it only works once correctly and then on every page reload I get a "Cannot read property 'findIndex' of undefined". It only works again if I remove the findIndex, reload and add it afterwards again (And then it only works one time again).
This is my vuex store:
export const state = () => ({
allHandhelds: [],
});
export const mutations = {
setHandhelds(state, allHandhelds) {
state.allHandhelds = allHandhelds;
},
};
export const actions = {
fetchAllHandhelds(context) {
return fetch(
"URLHERE"
)
.then((response) => response.json())
.then((data) => {
context.commit("setHandhelds", data);
})
.catch((err) => console.error(err));
},
};
This is my template:
<template>
<div id="homepage">
<div>{{ handheldID2() }}</div>
</div>
</template>
And this is my script including the method and how I import the data from vuex:
<script>
import { mapActions, mapGetters } from "vuex";
export default {
data() {
return {};
},
computed: {
...mapGetters(["allHandhelds"]),
},
created() {
this.fetchAllHandhelds();
},
methods: {
...mapActions(["fetchAllHandhelds"]),
handheldID2() {
return this.allHandhelds.values[0].findIndex(
(el) => el === "Form Factor"
);
},
},
};
</script>
My thoughts:
It seems like I'm storing the data not correctly. After a page refresh the Method doesn't seem to have access to the right data anymore.