Challenges I'm Facing with my Vue.js API Integration using axios

I am currently working on a bookstore application using Vue.js. The book data is stored in this API . However, I am encountering issues displaying the information on my HTML page with the provided function and I am struggling to identify the root cause:

<div id="list-books" v-if="books && books.length">
  <div>Cover page: <strong>{{ books }}</strong></div>
  <div>Details: <strong>{{ books.detalle }}</strong></div>
  <div>Title: <strong>{{books.titulo}}</strong></div>
  <div>Description: <strong >{{books.descripcion}}</strong></div>
  <div>Language: <strong>{{books.idioma}}</strong></div>
</div>
<div class="text-center" v-else> No results! </div>
new Vue({
  el: "#vue-app",
  data() {
    return {
      title: "Ubiqum Bookstore",
      books: []
    };
  },
  methods: {
    getAPI() {
      axios
        .get("https://api.myjson.com/bins/1h3vb3")
        .then(response => {
          this.books = response;
        })
        .catch(e => {
          console.log("No found!");
        });
    }
  }
});

Answer №1

axios.get resolves to a Response, which holds the received data in the data property. In your code, you incorrectly assigned this.books to response, which is the entire Response object. You should instead use response.data.books:

axios.get(...).then(response => this.books = response.data.books)

Furthermore, to display a list of items, utilize v-for="book in books" like so:

<div v-for="book in books">
  <div>Details: <strong>{{ book.details }}</strong></div>
  <div>Title: <strong>{{ book.title }}</strong></div>
  <div>Description: <strong >{{ book.description }}</strong></div>
  <div>Language: <strong>{{ book.language }}</strong></div>
</div>

new Vue({
  el: '#vue-app',
  data() {
    return {
      title: "Ubiqum Bookstore",
      books: []
    };
  },
  methods: {
    getAPI() {
      axios
        .get("https://api.myjson.com/bins/1h3vb3")
        .then(response => {
          this.books = response.data.books;
        })
        .catch(e => {
          console.log("Not found!");
        });
    }
  }
})
.book {
  margin: 1rem;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f6808393b6c4d8c0d8c7c7">[email protected]</a>/dist/vue.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f8998091978bb8c8d6c9c1d6ca">[email protected]</a>/dist/axios.min.js"></script>

<div id="vue-app">
  <button @click="getAPI">Get data from API</button>
  <div id="list-books" class="book" v-if="books" v-for="book in books">
<!--     <div>Cover page: <strong>{{ books }}</strong></div> -->
    <div>Details: <strong>{{ book.details }}</strong></div>
    <div>Title: <strong>{{book.title}}</strong></div>
    <div>Description: <strong >{{book.description}}</strong></div>
    <div>Language: <strong>{{book.language}}</strong></div>
  </div>
  <div class="text-center" v-else> No results! </div>
</div>

Answer №2

It seems like there may be a missing piece in the code you've shared. While you have declared your getAPI method, it appears that you haven't actually called it anywhere.

To make sure it runs properly, you should include something similar to this:

...
data() {
  return {
    title: "Ubiqum Bookstore",
    books: []
  };
},
mounted() {
  this.getAPI();
},
methods: {
  getAPI() {
    ...
  }
}

UPDATE In the following code snippet below, there are a few errors that need to be addressed:

  • The reason why your books array was empty is because this.books = response; assigned the entire response object instead of the data. You should use
    this.books = response.data.books;
    instead.
  • You also forgot to include a v-for loop to iterate through the results.
<div class="book" v-for="book in books">
...
</div>

Here is a working jsfiddle example: https://jsfiddle.net/6bytes/ufbaem0j/8/

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

Is it feasible to utilize an array of properties with the "item-text" attribute in Vuetify?

<v-autocomplete v-model="friends" :disabled="isUpdating" :items="people" label="Select" item-text="name" <!-- Array ['name', 'id', 'value'] can be used her ...

Having trouble with jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

How to Use a Discord Bot to Send a Message (Step-by-Step Guide)

I am looking for a simple way to send a message using my discord bot, but everything I have found online seems too complex for me to understand and implement. require("dotenv").config(); //to start process from .env file const { Client, GatewayIn ...

Navigate back to the parent directory in Node.js using the method fs.readFileSync

I'm restructuring the folder layout for my discord.js bot. To add more organization, I created a "src" folder to hold all js files. However, I'm facing an issue when trying to use readFileSync on a json file that is outside the src folder. Let&ap ...

Using React to create an onScroll event listener within a mapped array

I am currently working on a setup where scrolling over an image mapped from an array updates the state with that image's coordinates, which in turn updates a Google Map. <CloudinaryContext cloudName="hcjmhcjf" fetchFormat="auto"> <div clas ...

The dropdown item in Tailwindcss is unexpectedly flying off the edge of the screen rather than appearing directly under the dropdown button

Currently, I am developing an application using Rails, Vue, and TailwindCss 1.0+ I am facing an issue while creating a dropdown menu for my products. When I click on the dropdown button, the items in the dropdown fly off to the edge of the screen instead ...

What is the method for updating the form action to alter the hash without causing a page reload?

My website is designed to show dynamic data based on the information following the '#' in the URL. Surprisingly, when I manually change this value in the URL, the page doesn't reload. However, if I modify it within a form on the site, the we ...

Is there a way to modify the value of a JavaScript object?

My React componentwillmount fetches data from an ExpressJS API using Axios and receives a JSON response, which is then converted to an object by Axios. [{"client_nick":"PlayTalk","connected_time_record":183710127},{"client_nick":"PlayTalk","connected_time ...

VuexFire Transformations

Can someone shed some light on the mysterious mutations: VuexFire.mutations line in this code snippet for Vuex v2? I'm a bit confused about where my actual mutations should go. Currently using Vuex v1 and everything seems fine, but considering an upgr ...

Guide for using express.js

Similar to how you can use to view the source code of all classes in Java, is there a resource available to view the source code of the express module? ...

Chrome reports a Javascript error: indicating that it is not recognizing the function

When working with a js file and html, I encountered an issue where one function works fine but another prompts an error in Chrome: Uncaught TypeError: specification_existing is not a function I'm puzzled as to why one function works while the othe ...

Trapped in the Web of Facebook OAuth

I've been struggling with this issue for a day now and I can't seem to pinpoint where I'm going wrong. I have experience working with JavaScript on the client side and recently started following a book tutorial. However, it appears that Face ...

Nested pages in the NextJS router do not properly highlight the active menu item

I am currently working with NextJS and facing an issue with setting active menu items using the router. While the 'top level' pages behave as expected, any page under a top level page does not get set as active. router.pathname == "/profile& ...

Map image showing only the tile layer in the top corner

My current project involves utilizing Ionic 5 and Vue.js. One of the screens in my project features a leaflet map that needs to cover most of the screen space. To implement this, I have integrated the Leaflet library for vue into my code. Here is a snippe ...

Can you create asynchronous code or functions without using Web APIs at all?

Even though JavaScript is single-threaded, I can't help but wonder about a function that takes an unusual amount of time without any involvement from web APIs like this: console.log("start") function banana() { let bananaCount = 10; while (b ...

What is the proper way to write a function that verifies the presence of a key in an object and then retrieves the associated value?

After holding out for a while hoping to stumble upon the solution, I've decided to give it a shot here on SO since I haven't found it yet. import { PDFViewer, MSViewer } from './viewerclasses' //attempting to incorporate a union of key ...

Dividing a JSON array by a specific key using lodash underscore

I'm on a quest to extract the distinct items in every column of a JSON array. Here is what I aim to convert : var items = [ {"name": "Type 1","id": 13}, {"name": "Type 2","id": 14}, {"name": "Type 3","id": 14}, {"name": "Type 3","id": 13}, {"na ...

What steps can I take to enhance the efficiency of this JavaScript DOM data manipulation algorithm?

Purpose I am working with a DOM that contains around 70 elements (divs with content). I have the need to move and toggle the display of these divs frequently and rapidly. Speed is crucial in this process. The trigger for moving and toggling these divs is ...

The type 'undefined' cannot be assigned to the type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

Verification Code for JWT This function is used to verify a jwt using typescript. public verify( token: string, secretOrPublicKey?: string | Buffer, options?: jwt.VerifyOptions ): Promise<object | string> { if (!secretOrPublicKey) { ...

The key to successful filtering in Next.js with Hasura is timing - it's always a step

I am fetching data from Hasura using useRecipe_Filter and passing the searchFilter state as a variable. It seems that every time I press a key, the UI updates with one keystroke delay before filtered data is passed to the results state. const SearchBar = ( ...