I am encountering an issue where the state remains undefined within my components, even when attempting to access it through the

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.

Answer №1

computed: {
  ...mapGetters({
    heading: 'getHeading',
    movies: 'getMovies',
  }),
},

The code snippet provided above is functioning correctly due to the usage of

v-if="!heading || !movies"
in your condition, along with the assignment of values to variables headings and movies within the computed properties.

When trying to use the code as shown below, it does not work because the variables used in the condition are not declared in your app.

To make the code below work, you can directly utilize the getter properties getMovies and getHeading in your app (similar to how you use data properties). By modifying your condition to

v-if="!getHeading|| !getMovies"
, it will work accordingly.

computed: {
  ...mapGetters(['getMovies', 'getHeading']),
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a tree structure from an array in JavaScript, including the parent id enclosed in brackets

Before dismissing this question as a duplicate, please listen to me. I am working with a json response in reactjs that looks like the following organisationUnits: [ { name: "0.Mzondo", id: "nW4j6JDVFGn", parent: { ...

Positioning Thumbnails with Jquery Cycle Plugin

Initially, my inquiry is quite similar to a question that was previously posted here. However, the difference lies in the fact that I am utilizing WordPress and the nextgen gallery plugin to handle my images. mygallery/image1.jpg mygallery/image2.jpg and ...

The exported JSON file from the editor is malfunctioning

After importing the obj file into the editor and exporting the geometry to a js file, I encountered an error in Firefox debug saying "Type Error: t1 is undefined". Interestingly, when I changed the model to the .js file exported by MaxExporter with both "E ...

Not able to handle axios error in a Vue/CLI project using VueJS

Hello, I am working on a feature that involves displaying an error message from an API using axios. Below is the code snippet: Case 1 ... <span class="badge" id="disconnected" v-if="noerror" >{{noerror.name}}</span& ...

Unable to maintain constant slide down feature for jQuery dropdown

I am currently working on a website for a client and I am still learning the ropes of jQuery. The website required a dropdown menu to display links to galleries in a list format instead of having them all on the navigation bar. However, I encountered an is ...

What is the method to retrieve a chat that has been ended with JavaScript SDK?

Whenever I attempt to retrieve a closed Twilio Conversation on the frontend using the JS SDK, I encounter a "Not found" error. Can closed conversations be fetched? My objective is to enable users to close a conversation while still having access to the m ...

angularjs reset file input form

Whenever I click publish, I want to clear my form: $scope.product = {}; $scope.upload = function(user) { var formData = new FormData; $scope.product.owner = user; for (key in $scope.product) { ...

Notifying the Player of Victory in a Javascript Tic Tac Toe Game: The Winning Alert

Recently, I decided to dive into Javascript and kick off my very first game project - a Tic Tac Toe game. If you're curious to see the code for my project, you can check it out here: Tic Tac Toe Project One feature I'm eager to implement is a n ...

What is the best way to access a cached value?

I am currently utilizing the node-cache-manager library to manage caching in my Node.js application. After successfully adding an item to the cache using the following code: import cacheManager from 'cache-manager'; const memoryCache = cacheMan ...

Determine whether a particular value is absent from a JSON object

I am looking to verify the absence of a specific value in the given object by filtering an array of strings. My goal is to determine if the values within the keys array are present in the JSON object I am iterating through. If any of the values are missin ...

What could be the reason for encountering an undefined variable when utilizing classes?

I am just beginning to learn JavaScript and I have a question. On line 7 of Index.js, why is the value of this.main undefined? Main.js class Main { constructor(hostname, port) { this.hostname = hostname; this.port = port; } ...

The current date is cycling back to the month before

There is a datetime received from my api as 2018-09-01T00:00:00.000Z, referred to as frame.scandate. Another date is generated within the program as 2018-09, simply known as scandate. These examples can represent any year/month combination. In my code: ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

What could be causing my React component to only render after pressing ctrl + shift + R?

I am facing an issue with my chrome extension where it only appears after refreshing the page using ctrl + shift + r. However, there is a new problem that arises when I click on a link that refreshes the page, causing the extension to disappear and requiri ...

Retrieve the attribute value from an HTML element in a JSON response using JavaScript

I received a JSON request result containing a blogger post. // API callback posts( { "version": "1.0", "encoding": "UTF-8", "entry": { "title": { "type": "text", "$t": "Vimeo Embed Video Post" ...

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...

Utilizing Custom HTTP Headers in Angular 2 to Enhance Request Handling

Within my Angular 2 project, I am implementing the use of Http (@angular/http) to communicate with my API. In order for these requests to be successful, specific headers, including a JWT header, must be included in each API request. My goal is to have an ...

Performing an HTTP request to itself in NodeJS/ExpressJS

Currently coding an NPM module that requires making an HTTP request to itself, which is the running web server. Here's an example: let url = "http://127.0.0.1:" + (process.env.PORT || 3000) + path; request(url, function(error, response, body){ ... ...

Sort the array by the elements in a separate array

Here is a filters array with three values: serviceCode1, serviceCode2, and serviceCode3. ['serviceCode1', 'serviceCode2', 'serviceCode3'] I have another array with approximately 78 records that I want to filter based on the a ...

How can you efficiently load the materials for a THREE.BoxGeometry using THREE.LoadingManager()?

I am looking to enhance the image quality of a geometry after user interaction by initially loading low-resolution assets and then switching to high-resolution assets when the user interacts with it. When using the following standard code: var materials = ...