Home > Enterprise >  VueJS doesn't show data on a component but shows on console
VueJS doesn't show data on a component but shows on console

Time:12-29

I have two pages - Books and Book. I am trying to show some data on my Book page after clicking the single item from the Books page.

I have managed to fetch the JSON file which lists all the items on the Books page as well as a link to navigate to the Book page by id.

The problem I am facing is I can't fetch the data which is returned by JSON on the Book page. The data is hidden but console.log(response.data) shows response data on console without a problem.

Here is the route-link from the Books page which navigates a single Book:

<router-link :to="'/books/'   book.id"> Link </router-link>

And here is my Book component script

<script>
import LibraryDataService from "../services/LibraryDataService";

export default {
  name: "Book",
  data() {
    return {
      book: "",
    };
  },

  methods: {
    getBook(id) {
      LibraryDataService.get(id)
        .then((response) => {
          this.book = response.data;
          console.log(response.data);
        })
        .catch((e) => {
          console.log(e);
        });
    },
  },

  mounted() {
    this.getBook(this.$route.params.id);
  },
};
</script>

Any help will be appreciated

CodePudding user response:

Try to wait for response:

async mounted() {
  await this.getBook(this.$route.params.id);
},

CodePudding user response:

I have been able to solve the issue by modifiying response.data on the getBook method as this.book = response.data[0];

  • Related