"Although Vuex data is present, an error is being logged in the JavaScript console

I'm utilizing Vuex to retrieve data from a URL and I need to use this data in computed properties in Vue.js. What could be causing the issue?

<script>
import {mapGetters, mapActions} from "vuex";
computed: {
    ...mapGetters(["ONE_FILM"]),
    allActors() {
        return this.ONE_FILM.actors.split(",")
    },
    allVoiceActors() {
        return this.ONE_FILM.rolesDuplicated.split(",")
    },
}
</script>

View image description here
//TypeError: this.ONE_FILM.actors is undefined

This is how my Vuex code is structured:

export default {
    state: {
        oneFilm: {
            actors:[],
            rolesDuplicated:[],
            relatedFilms:[],
            facts:[],
            reviews:[]
        }
    },
    actions: {
        async getFilm({commit}, id) {
            const data = await fetch(URL);
            const dataResponse = await data.json();
            const film = dataResponse.data[id]
            commit("setOneFilmData", film)
        },
    },
    mutations: {
        setOneFilmData(state, film) {
            state.oneFilm = film
        },
    },
    getters: {
        ONE_FILM(state) {
            return state.oneFilm;
        },
    }
}

Answer №1

Below is the improved Vuex store incorporating actors and rolesDuplicated as empty strings:

export default {
  state: {
    oneFilm: {
      actors: "", // Initialize as empty string
      rolesDuplicated: "", // Initialize as empty string
      relatedFilms: [],
      facts: [],
      reviews: []
    }
  },
  // ... rest of the code
}

With this adjustment, your computed properties in the component should function properly without any "undefined" errors.

Ensure that the data fetched from the URL is accurately mapped to the Vuex store to populate the state with the film data. Confirm that the getFilm action is invoked with the correct ID to retrieve the film data from the API.

If the data retrieved from the URL is already an object (not an array), update the mutation to combine the fetched film data into the oneFilm property rather than setting it directly:

mutations: {
  setOneFilmData(state, film) {
    state.oneFilm = { ...state.oneFilm, ...film };
  },
},

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

Display or conceal HTML content based on the input's property type

Looking to toggle the visibility of an icon on my input based on the prop type. If the type is set to password, the icon will be displayed for toggling between visible and hidden password; if the type is not password, the icon should be hidden by setting ...

Can Regex expressions be utilized within the nodeJS aws sdk?

Running this AWS CLI command allows me to retrieve the correct images created within the past 45 days. aws ec2 describe-images --region us-east-1 --owners self -- query'Images[CreationDate<`2021-12-18`] | sort_by(@, &CreationDate)[].Name&apos ...

Do we need to use aria-labelledby if we already have label and input associated with "for" and "id"?

Here is the HTML structure for the Text Field component from Adobe Spectrum: The <label> element has a for attribute and the <input> has an id which allows screen readers to read out the label when the input is focused. So, why is aria-label ...

Guide to showcasing an image on an HTML page using HTTP header

I have an HTML page with a basic layout that includes a single button. When this button is clicked, it needs to trigger an HTTP request to a specific URL while including an Accept header for GET requests. The response from the HTTP URL will vary depending ...

Setting a TypeScript collection field within an object prior to sending an HTTP POST request

Encountered an issue while attempting to POST an Object (User). The error message appeared when structuring it as follows: Below is the model class used: export class User { userRoles: Set<UserRole>; id: number; } In my TypeScript file, I included ...

What could be the reason behind encountering an NaN error while using these particular functions?

I recently delved into the world of JavaScript, starting my learning journey about two months ago. While going through a few tutorials, I stumbled upon an intriguing project idea. However, I've hit a roadblock that's impeding my progress. Every t ...

Enabling real-time notifications through Express 4 middleware with socket.io integration

I am in the process of developing a real-time notification system utilizing socket.io. Here is the current server-side code I have implemented: bin/www: var app = require('../app'); var server = http.createServer(app); var io = app.io io.attac ...

AngularJS - "Refrain from replicating items in a repeater"

I am facing an issue with creating HTML textarea elements for each member of an array. Despite consulting the AngularJS documentation and attempting different track by expressions, I am unable to render them. The problem arises when a user inputs the same ...

Tips to prevent encountering the "The response was not received before the message port closed" error while utilizing the await function in the listener

I'm currently in the process of developing a chrome extension using the node module "chrome-extension-async" and have encountered an issue with utilizing await within the background listener. In my setup, the content.js file sends a message to the ba ...

Guide to adding Angular 2 components to various locations in the DOM of a vanilla JavaScript webpage

Scenario: A customer is interested in creating a library of Angular 2 components that offer a technology-agnostic interface to developers. This allows developers to use plain JavaScript without needing knowledge of the internal workings of the library. Th ...

Utilizing Vue's v-for directive to display computed properties once they have been fully loaded

Utilizing the v-for directive to loop through a computed property, which is dependent on a data attribute initialized as null. I'm planning to load it during the beforeMount lifecycle hook. Here's a simplified version of the code: <th v-for= ...

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

When utilizing a React styled component, it functions smoothly during development but triggers a build error when in production

Recently, I encountered a strange issue with my code. I have a styled component div that wraps around another component in this manner: <ContentWidget> <BookDay /> </ContentWidget> (The Bookday component returns an empty div so there ...

Adaptable material for collapsible panels

I'm facing a challenge with implementing an accordion menu. My goal is to have a 4 column layout that transforms into an accordion menu when the browser width is less than 600px. It almost works as intended, but there's a glitch. If you start at ...

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...

JavaScript/CSS manipulation: The power of overriding animation-fill-mode

When animating text using CSS keyframes, I use animation-fill-mode: forwards to maintain the final look of the animation. For example: #my-text { opacity: 0; } .show-me { animation-name: show-me; animation-duration: 2s; animation-fill-mod ...

Establishing Connections to Multiple MySQL Databases Using Node.js

I'm struggling to incorporate a dropdown menu that displays all the databases from a set host. The idea is to allow users to choose a database from the drop-down and generate a report. However, I can't figure out how to connect to the host and po ...

Transforming a JSON into a JavaScript object using deserialization

Within a Java server application, there exists a string that can be accessed through AJAX. The structure of this string is exemplified below: var json = [{ "adjacencies": [ { "nodeTo": "graphnode2", "nodeFrom": "graphnode1" ...

webpackDevMiddleware does not automatically trigger a reload

Currently, I have implemented webpack dev middleware in my project like this: const compiledWebpack = webpack(config), app = express(), devMiddleware = webpackDevMiddleware(compiledWebpack, { historyApiFallbac ...

Is it advisable to use an autosubmit form for processing online payments?

Situation: In the process of upgrading an outdated PHP 4 website, I am tasked with implementing an online payment system. This will involve utilizing an external payment platform/gateway to handle transactions. After a customer has completed their order ...