Utilize an API call to fetch data and seamlessly showcase it on the webpage using Vue.js

I have created an API and defined it in my TypeScript file

const Book = {
   async getBookType(intID: string): Promise<Book[]> {
        // const intId = API.Product.getCurrentId();
        const intId = '';
        const response = await http.get('/myasset/booktypes', {
            params: {
            int_id: intID,
            },
        });
        const bookTypes = JSON.parse(JSON.stringify(response.data));
        return bookTypes;
   },
};

Now, on my bookpage.vue, I want to fetch the API response and display the data on the page.

Could you provide an example of how I can achieve this using Vue.js?

When I examined the response body in Postman, here is what I found:

"adventure": 1,
"biography": 2,
"drama": 1,
"romance": 1

My goal is to simply display this data on the page.

Thank you in advance.

Answer №1

Here is a different approach to solve the problem :

new Vue({
  el: '#app',
  data: {
    response: {
      data: {}
    }
  },
  mounted() {
    // Instead of calling an API, for this demo I will simulate the response.
    this.response.data = {
      "adventure": 1,
      "biography": 2,
      "drama": 1,
      "romance": 1
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul>
    <li v-for="(item, index) in Object.keys(response.data)" :key="index">
      {{ item }} - {{ response.data[item] }}
    </li>
  </ul>
</div>

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

update icon when a router link becomes active

<div class="menuItem mb-3" *ngFor="let menuItem of menuItems"> <a routerLink="{{menuItem.link}}" routerLinkActive="active"> <img src="{{menuItem.icon}}" alt="{{menuItem.name}}" /> <p class="text-center f-12">{{me ...

Step-by-step guide on uploading an image file using Nextjs

I am attempting to achieve the following: Upload an image file to a Next.js application Process it using cjwbw/real-esrgan:d0ee3d708c9b911f122a4ad90046c5d26a0293b99476d697f6bb7f2e251ce2d4 Retrieve the enhanced version of the image Is there anyone who can ...

Refreshing the page in VueJs does not trigger the axios function

I've encountered an issue with my VueJs app after purchasing the Vuexy template from ThemeForest. I created a new component called CountryTable.vue, and while it works initially, it fails to display data when I refresh the page. It only shows data whe ...

Elements with absolute positioning are preventing drag events from executing

Struggling to create a slider and encountering an issue. The problem lies in absolute items blocking slider drag events. I need a solution that allows dragging the underlying image through absolute positioned items. Any ideas on how to achieve this? MANY T ...

Incorporate the Get Your Guide Widget into an Angular2 component

Currently, I am attempting to embed a "Get Your Guide" Widget within an Angular2 application. Although the script in index.html is being requested successfully, I am facing difficulties adding it to the HTML of the component. <script async defer src=" ...

Preventing Undefined Values in RxJS Observables: A Guide

I am facing an issue with passing the result of a GET request from Observable to Observer. The problem lies in the fact that the value becomes undefined because it communicates with the observer before the GET execution finishes. observer:Observer<a ...

Convert the union into a mapped structure

Starting with the given Union type: type Union = { type: 'A', a: string } | { type: 'B', b: number } The end goal is to transform it into this MappedUnion type: type MappedUnion = { A: { type: 'A', a: string } B: { ...

Struggling to launch nuxt application on Digital Ocean due to issues with health checks

I developed a straightforward Nuxt app and successfully pushed it to a GitHub repository from the terminal. Next, I linked my repository to the Digital Ocean app functionality for deployment. Despite a successful build, the launch fails with the following ...

Is there a way to connect a Button to a different page in VUE.JS?

I currently have a button that needs to be linked to another page. This is the code I am working with at the moment. How can we write this login functionality in vue.js? It should direct users to the page "/shop/customer/login" <div class="space-x ...

An issue has been encountered: No NgModule metadata was discovered for 'AppModule' in the ngx-rocket Metronic theme

Task List [ ] Initialize [x] Build [x] Serve [ ] Test [ ] End-to-End test [ ] Generate [ ] Add [ ] Update [ ] Lint [ ] Internationalization [ ] Run [ ] Configure [ ] Help [ ] Version [ ] Documentation Is this a regression? This issue started occurring ...

[Vue alert]: Necessary prop not supplied: "productInfo"

As someone who is still learning Vue, I might be missing something obvious here. Whenever I try to run my .vue file, I keep encountering the error: [Vue warn]: Missing required prop: "productInfo". The error seems to originate from ProductSlider.vue. Prod ...

Unexpected results observed in enumerators within typescript

Could someone clarify the results that I am seeing from the code below? enum days { sun = 1, mon = 0, tues }; console.log(days[1]); // outputs tues // should output -- mon console.log(days[0]); // outputs mon // should output -- sun Furthermore, how ...

The impact of redefining TypeScript constructor parameter properties when inheriting classes

Exploring the inner workings of TypeScript from a more theoretical perspective. Referencing this particular discussion and drawing from personal experiences, it appears that there are two distinct methods for handling constructor parameter properties when ...

Testing Angular HTTP error handlers: A comprehensive guide

Below, you will find an example of code snippet: this.paymentTypesService.updatePaymentTypesOrder('cashout', newOrder).subscribe(() => { this.notificationsService.success( 'Success!', `Order change saved successfully`, ...

Compiling Typescript with module imports

In my project, I am working with two files named a.ts and b.ts. The interesting part is that file b exports something for file a to use. While the TypeScript compiler handles this setup perfectly, it fails to generate valid output for a browser environment ...

I'm puzzled as to why a div tag suddenly becomes invisible when I attempt to link it with a v-for directive in my code

I am facing an issue with the div tag assigned to the log class. My objective is to populate the text using data retrieved from the API response. However, when I attempt to include the v-for directive, the entire div mysteriously disappears from the brow ...

Testing the number of times module functions are called using Jest

As someone who is relatively new to JavaScript and Jest, I am faced with a particular challenge in my testing. jest.mock('./db' , ()=>{ saveProduct: (product)=>{ //someLogic return }, updateProduct: (product)=>{ ...

What steps should I take to resolve an unhandled promise error in a React TypeScript application while making an axios POST request?

I am currently working on a .tsx file to implement adding an enterprise feature. Although I can input data, clicking the submit button does not trigger any action. My application includes a page that has a button for adding a new enterprise. Upon clickin ...

How can I retrieve the object returned by an external API in VueJS?

I recently integrated the hcaptcha widget into my login component by utilizing the following package: https://github.com/hCaptcha/vue-hcaptcha. The challenge is functioning correctly on the front end. Upon inspecting the response object in the network tab ...

Tips for refreshing retrieved data from the server upon page creation in Vue.JS

Upon page load, data is retrieved from the server and displayed in a table format like the one shown below: <tr v-for="option in options"> <td> < ...