Home > Software engineering >  Why is Axios data undefined when stored in a variable?
Why is Axios data undefined when stored in a variable?

Time:09-27

I have the following code I am working on. This is implemented on a Vue app and uses a number of methods which each return with an Axios promise. I am trying to chain these so when a new review is submitted, the server checks if a movie exists already. If not, it creates a new movie. Then it should create a new review using postReview with a parameter of movieId. A movieId is required to create a new review. The methods checkMovieExists() and postMovie() both return a movieId as a response.

The problem is that when I log x.data() or y.data() into the console, the movieId is displayed correctly. However, if I assign x.data or y.data to movieId, it is undefined. This means I can't use it as a parameter to post a movie.

submit() {
      let movieId = 0;
      this.checkMovieExists(this.movie.imdb_id)
        .then((x) => {
          console.log(x.data);
          if (x.data == 404) {
            this.postMovie(this.movie.imdb_id, this.movie.original_title).then(
              (y) => {
                console.log(y.data); //Displays correctly
                movieId = y.data;
                console.log(movieId); //Displays as undefined
              }
            );
          } else {
            movieId = x.data;
          }
        })
        .then(this.postReview(movieId));
    },

(Btw, I am aware of the bug where a movie id is 404. This is my next task!)

CodePudding user response:

I would advise you to stay away from callback hell and to use async/await.

async submit() {
  let movieId = 0;
  const checkMovieResponse = await this.checkMovieExists(this.movie.imdb_id);
  if (checkMovieResponse.data == 404) {
    const postMovieResponse = await this.postMovie(this.movie.imdb_id, this.movie.original_title);
    movieId = postMovieResponse.data;
  }
  else {
    movieId = checkMovieResponse.data;
  }
  await this.postReview(movieId);
}

Your problem should be fixed with my solution (there was an asynchronous issue with your code).
Your postMovie callback was executed after your checkMovie callback (causing an "undefined" (should be 0 by just reading your code) movieId in your postReview method).
If for some reasons, you cannot use async/await, here is your "fixed" code:

submit() {
  this.checkMovieExists(this.movie.imdb_id)
    .then((x) => {
      if (x.data == 404) {
        this.postMovie(this.movie.imdb_id, this.movie.original_title).then(
          (y) => {
            this.postReview(y.data)
          }
        );
      } else {
        this.postReview(x.data);
      }
    });
}

By the way, if the data from your Axios response is a number (for your identifier), I would advise you to use the === operator instead of the ==.
Good luck with your project!

  • Related