Home » vue » Why is 'route.params.id' unavailable/undefined in setup method?

Why is 'route.params.id' unavailable/undefined in setup method?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m working with vue-router and Vue 3. I have a view where I’d like to take the router url and use it to call a method to access an API. This method returns a promise I can use to populate my page. When calling my method with ‘route.params.id’, it says that the parameter is undefined. When I do console.log(route.params.id), it displays correctly in console. I’ve tried using a computed property instead, but I had the same issue.

Setup code:

import { ref } from "vue";
import MovieApiService from "../api/MovieApiService";
import { useRoute } from "vue-router";

export default {
  setup() {
    const movie = ref([]);
    const route = useRoute();

    MovieApiService.getMovie(route.params.id).then((response) => {
      movie.value = response.data.results;
    });

    return {
      movie,
    };
  },
  method: {},
};

Method being called:

static getMovie(body: GetMovieByTmdbId) {
    return axios.get(
      `https://api.themoviedb.org/3/movie/${body.id}?api_key=${apiKey}`
    );
  }

Here’s what I tried to compute the property instead, with the same result.

setup() {
    const route = useRoute();
    const id = computed(()=>{return route.params.id})

    const movie = ref([]);

    getMovie(id).then((response) => {
      movie.value = response.data.results;
      console.log(movie.value);
    });

How should I ensure this value is available when I call my method?

Answers:

You are giving route.params.id as a variable to getMovie(body).

You are then using body.id in your URL. This would equal route.params.id.id which is not defined.

Use body in your URL, or change the parameter to id so is makes more sense.

Like this:

...
const route = useRoute();
MovieApiService.getMovie(route.params.id).then((response) => {
  movie.value = response.data.results;
});
...
const getMovie = (id) => {
  return axios.get(
    `https://api.themoviedb.org/3/movie/${id}?api_key=${apiKey}`
  );
}