Tips for declaring a data variable in Vue with the help of APIs

I'm currently working on a project where I am integrating movie data from an API (TMDb) using Vue Routers. I have a component named 'MovieList' where I am fetching data from the API.
Below is the data structure:

data() {
  return {
    movies: []
  }
}

Here are the methods being used:

methods: {
  getMovies: () => new Promise((resolve, reject) => {
    const url = `https://api.themoviedb.org/3/discover/movie?api_key=MyAPI`;
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(JSON.parse(xhr.responseText).results);
      } else {
        reject(Error(xhr.statusText));
      }
    }
    xhr.send();
  })
}

and here is the mounted method:

mounted() {
  this.getMovies().then(
    result => processData(result)
  )
  function processData(result) {
    result.forEach((el) =>  {
      this.movies = el
    })
  }
}

My goal is to populate the 'movies' array with the data fetched from the API.
You can view a screenshot here: https://i.sstatic.net/zw7S1.png

Additionally, I am encountering an error in the console:

MovieList.vue?ea6b:34 Uncaught (in promise) TypeError: Cannot set property 'movies' of undefined
    at eval (MovieList.vue?ea6b:36)
    at Array.forEach (<anonymous>)
    at processData (MovieList.vue?ea6b:35)
    at eval (MovieList.vue?ea6b:30)

Thank you in advance for any assistance you can provide!

Answer №1

Not sure about the data type returned by the API, but give this a shot:

mounted() {
    let _self = this
    _self.fetchData().then(response => {
        _self.data = response
    })
}

Answer №2

The implementation within the mounted hook seems unconventional.

To populate the movies array with the result, you simply need to:

export default {
  data: () => ({ movies: [] }),

  // Utilize the "created" hook for earlier execution
  // without any apparent reason for delay
  async created () {
    // Assign the result array directly to "movies"
    this.movies = await this.getMovies()
  },


  methods: {
    // No changes needed to the "getMovies" method 
    // Modernize your approach beyond XMLHttpRequest
    async getMovies () {
      const res = await fetch('https://api.themoviedb.org/3/discover/movie?api_key=MyAPI')
      if (!res.ok) {
        throw res
      }
      return (await res.json()).results
    }
  }
}

The issue lies in your get function where this does not reference the Vue instance.

Furthermore, attempting to overwrite movies with each result in the array will only retain the final result.

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

Using jQuery to filter or duplicate options in a select box - a step-by-step guide!

I am struggling with filtering options in two select boxes. One contains projects and the other contains people: <select id="project"> <option data-person_ids="[75,76,77]">None</option> <option data-person_ids="[77]">Project A& ...

Tips for transferring data via ajax to rails 3. The jQuery function is ensuring the string is properly handled

I am attempting to achieve the following: $.ajax({ type: "PUT", url: /example, data: {_method: "put", "foo_model[bar_attribute]": value_var } }); It is working as expected, but I need to dynamically construct the part foo_model[bar_attribute]. ...

AngularJS Fusion Charts are experiencing issues with events not functioning properly

In my Angular application, I am attempting to capture the dataplotClick event in a pie2d chart of Fusion Charts. I came across an example of a bar chart with events here. When I directly create the events object within the main scope, everything works as e ...

After refreshing the page, the Vue instance that was imported is not defined within the created or mounted hooks

I am attempting to integrate a feature in Vue that will automatically log in the user after the page is reloaded. I have imported the Vue instance into a module responsible for sending HTTP requests. This module is then imported into the main component of ...

Eliminate an array from another array if a specific value is present in an object

I've been struggling with removing an entire array if it contains an object with a certain value within. I've searched high and low, but haven't been able to find a solution that fits my specific problem. In my data structure, I have arrays ...

Conceal the div element if the screen size drops below a certain threshold

Is it possible to hide a div element when the browser width is less than or equal to 1026px using CSS, like this: @media only screen and (min-width: 1140px) {}? If not, what are some alternative solutions? Additional information: When hiding the div eleme ...

multiple elements sharing identical CSS styling

For each component, I made separate CSS files and imported them accordingly. However, despite the individual styling efforts, all components seem to have the same appearance. I specifically worked on styling an image differently for two components, but w ...

What is the preferred method for updating a variable value - Ajax or PHP?

I'm in the process of creating a dropdown survey for new visitors using cookies to collect data, but I'm a bit confused on how to implement it. If a button is clicked, the onClick event will trigger var answer1 = answer1 + 1 , or something simil ...

Present XML data on an HTML page to generate interactive form features

I have an application that features a checkbox tree. I would like to automatically pre-select those checkboxes if the user had previously checked them. To achieve this, I receive XML data from my backend Perl script which contains information on which che ...

"Error: Command 'npm' is not recognized as a valid internal or external command" encountered while using create-react-app

Why won't npm work for me? I've been trying to dive into the world of React and kickstart my learning journey. With Node installed, along with the create-react-app package, I thought I was all set. When I run commands like npm -v or create-reac ...

Webpack can generate separate compiled files in addition to the bundle

Currently, I am utilizing the webpack loader ts-loader to convert typescript source files into a javascript bundle. My goal now is to not only save the compiled javascript bundle but also the individual compiled javascript files. While I have experience ...

The Angular Google Maps Directive zooms in too much after the "place_changed" event has fired

Currently, I am developing a store locator app for DHL accessible at storefinder.hashfff.com/app/index.html For this project, I decided to utilize the angular-google-maps library for its features. However, in hindsight, working directly with the Google Ma ...

Utilizing constants within if statements in JavaScript/TypeScript

When working with PHP, it is common practice to declare variables inside if statement parenthesis like so: if ($myvar = myfunction()) { // perform actions using $myvar } Is there an equivalent approach in JavaScript or TypeScript?: if (const myvar = myf ...

Creating a fresh instance of an Object from a Service that leverages the $resource

I have been enhancing my existing code to improve its functionality by creating two objects for interacting with a RESTful API. Before, I utilized $http to retrieve the data and return the promise. I would then add some actions using .then and repeat the ...

How can I use JQuery to enable or disable checkboxes upon loading?

I am looking to implement a feature where the checkboxes are enabled when the .group is checked and disabled when it is unchecked. Although I can toggle between them, I'm facing difficulty in disabling the unchecked checkbox using the .group. Upon lo ...

Securing routes with passport.js in a MEAN Stack setting

I am facing an issue with securing individual routes in my admin panel using passport.js. The user signup functionality is working fine, and I am able to login successfully. However, the req.isAuthenticated() function always returns false, preventing me fr ...

The select 2 control feature appears to be missing from the Vue.js implementation

https://i.stack.imgur.com/QnTam.pngI am facing a challenge with my Vue.js setup where I need to bind a select2 using a directive instead of a template. Due to constraints, I am required to use an asp:DropDownList, resulting in the select boxes being displa ...

What is the most effective method for informing the browser about changes in the database?

I've been working with django for about 6 months now and it has been effective for the websites I create. However, I recently encountered an issue while developing a website where users receive notifications whenever another user updates a blog post. ...

Vanilla JavaScript error: Unable to access property

I am working on implementing a header with a logo and navigation that includes a menu toggle link for smaller viewports. My goal is to achieve this using Vanilla JS instead of jQuery. However, when I click on the menu toggle link, I encounter the followin ...

Achieve a seamless redirection to the 404 component in Angular without altering the browser URL, while ensuring that the browsing

Whenever my backend sends a 404 error (indicating that the URL is valid, but the requested resource is not found, such as http://localhost:4200/post/title-not-exist), I need Angular to automatically redirect to my NotFoundComponent without altering the URL ...