"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

Bind a collection of Firestore documents dynamically using Vuexfire

I currently have a collection of firebase documents stored in a vuex state that is dynamically updated. My goal is to bind these documents with vuexfire dynamically as they are added or removed from the list. state: { docsToBind: [], // This array is dy ...

Adding a border in jQuery or Javascript to highlight empty form fields

After making the decision to dive into the world of Javascript, I've been dedicated to perfecting a script that will encase empty elements with a border right before the user submits a form. My ultimate goal is to implement live validation in the form ...

Angular: Dynamically changing checkbox's status from parent

I'm in the process of developing a switcher component that can be reused. The key requirement is that the state of the switch should only change after an API call is made at the parent component level. If the API call is successful, then the state cha ...

An issue arose in Leaflet where drawing on the map became impossible after making an update to a marker's position

I have been working with Leaflet, Leaflet-draw, and Cordova Geolocation. Initially, when the map is loaded in globe view, drawing works perfectly. However, when the locate function is called to update the map center and marker position, drawing becomes imp ...

Retrieve the data of elements that have been clicked using jQuery

I am struggling with a particular issue and would appreciate some assistance. Recently, I've been working on developing buttons that, when clicked, add data to a form for submission. An example of the code structure is as follows: <div> < ...

Transfer attributes, but have exclusions in React

At times, we all have a common practice of wrapping DOM elements in custom components. <CustomComponet id="abc" title="abc" nonDomProp="abc" ...andsoforth /> In this example, the custom component wraps a button with pr ...

Apple Safari 14.0.3 restricts JavaScript from setting a cookie expiry date beyond one week from the current date

This is my second time reaching out with this question, but after plenty of trial and error experimentation, I have gathered much more information to share. I have been attempting different methods to set a cookie in Safari using JavaScript 'document ...

Encountering Issue in Vue 3: Difficulty retrieving parameter values upon route change

Currently, I have coded a function called chooseProject(e): chooseProject(e) { let token = this.extractFirstText( e.title ); let userId = this.projects.user_id; this.$router.push('/dashboard/'+token ); localStorage.setItem( & ...

Issue with dropdown list removeClass function

I am encountering an issue with the Jquery dropdown list click function. The addClass method is working properly, but the removeClass method is not functioning as expected. When I click on the dropdown list, it does not hide. Here is a live demo: http://j ...

Is it possible to fulfill a promise within an if statement?

I'm fairly new to using promises in JavaScript, and I am currently facing an issue where a function needs to execute before running some additional code in another function. The problem arises when the promised function includes an if statement that l ...

After mapping the elements of the array twice, generate a new array

Two differently formatted bits of data may be received, each requiring different character stripping methods. The variable names are temporary and will be changed once the function is operational. const cut = flatten.map(obj => { return obj.file. ...

The onClickOutside feature of VueUse does not respond to the right-click function

Currently experimenting with the onClickOutside method, but encountering an issue where it only responds to clicks outside using the left mouse button. Seeking a way to make it work with the right mouse button as well. Any ideas on how to achieve this? Po ...

Having issues with retrieving latitude and longitude data from the Geocoding API in Node.js when using the OpenWeather API

I attempted to create a program in node.js that utilizes the openweather API. The idea was for the user to input a city name, then use the Geocoding API to extract the latitude and longitude coordinates, and finally retrieve weather data from the current w ...

Filter search results using selected region from dropdown menu

I have been attempting to retrieve the value from a dropdown list and customize the search functionality specifically for the selected field. The client should only be able to search within the chosen zone in the dropdown. I have been searching for a solut ...

Unable to receive Ajax response

My current programming setup involves using a combination of JavaScript and PHP to implement an Ajax code. However, at this point in time, the outcome is showing up as undefined. To circumvent this issue, I have resorted to utilizing localStorage to trans ...

When should separate controllers be created for a list of values in a Laravel REST API?

Imagine I have a straightforward API for user registration. This API collects basic information like Name, email, state, gender, and marital status for each user. I already have database tables pre-populated with ids for state, gender, and marital status o ...

Is there a method in JS/jQuery to fill my input field with a constant string and ensure leading zeros are included?

I am looking to create an input textbox that starts with a fixed string followed by up to 6 leading zeros. As the user types in the input box, the leading zeros will be automatically removed once the maximum length of 6 characters is reached. The initial s ...

I am interested in delivering a blended, divided response containing JSON and a string using Express

I am currently in the process of integrating ChatGPT into my Node/Express project and I have a specific requirement. I would like to initially send some metadata in JSON format to the client before streaming the response from ChatGPT as it comes in. Every ...

Having trouble parsing a JSON string in your JavaScript code?

As a java developer transitioning to JavaScript, I'm faced with the task of parsing a JSON string retrieved from a WebService. Here is the JSON String: { "myArrayList": [ { "myHashMap": { "firstName": "Clara", ...

Ways to properly close open HTML tags using node.js?

Have you ever encountered a situation where user-entered content from a database or similar source only contains the opening tag without the closing tag? This can disrupt the layout of your website. Is there a way to fix this issue using Node.js on the s ...