Having an issue with my store and component setup. I have a component where I fetch data from an API in the created()
hook to update the state, and then use mapGetters
in the computed
section to access this state. However, nothing is rendering on the screen even though I've added a v-if
directive to check for undefined values.
I have confirmed in Vue devtools that the state updates correctly and data is fetched from the API. I've tried various solutions found online but only adding local component data alongside the store data worked, which isn't ideal due to data duplication.
movies.js (store)
import axios from 'axios';
const state = {
heading: '',
movies: [],
};
const getters = {
getMovies: (state) => state.movies,
getHeading: (state) => state.heading,
};
const actions = {
async fetchTopRatedMovies({ commit }) {
const res = await axios.get(
`https://api.themoviedb.org/3/movie/top_rated?api_key=${process.env.VUE_APP_THEMOVIEDB_API_KEY}&language=en-US&page=1`
);
commit('setMovies', res.data.results);
commit('setHeading', 'Top Rated Movies');
},
};
const mutations = {
setMovies: (state, movies) => (state.movies = movies),
setHeading: (state, heading) => (state.heading = heading),
};
export default {
state,
getters,
actions,
mutations,
};
Movies.vue (component)
<template>
<div v-if="!heading || !movies">
<Spinner />
</div>
<div v-else>
<h5 class="center">{{ heading }}</h5>
<div v-for="movie in movies" :key="movie.id">
<p>{{ movie.title }}</p>
</div>
</div>
</template>
<script>
import Spinner from '../layout/Spinner';
import { mapActions, mapGetters } from 'vuex';
export default {
name: 'Movies',
components: {
Spinner,
},
methods: {
...mapActions(['fetchTopRatedMovies']),
},
computed: {
...mapGetters(['getMovies', 'getHeading']),
},
created() {
this.fetchTopRatedMovies();
},
};
</script>
<style></style>
To solve this, changing computed
to:
computed: {
...mapGetters({
heading: 'getHeading',
movies: 'getMovies',
}),
},
resolved the issue, but it's unclear why it needed to be done this way when the documentation suggests otherwise.