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

There was an error with the response code of 500 on the development server for react-native

An issue has been encountered on the node.js window: error: bundling failed: Error: Unable to resolve module react-native-gesture-handler from node_modules\@react-navigation\native\src\Scrollables.js: react-native-gesture-handler could ...

Having trouble importing my function component into a router in reactjs. Need some guidance on how to properly set it up

I am working on a Slider component function called export default Slider. In my App.js file, I have the following code: function App() { return ( <Router> <Routes> <Route exact path='/' element={<Home />} /> ...

The indexOf function is not compatible with AngularJS controllers

My dilemma revolves around an object that is evidently a string, given that I can access the string using: console.log(sender) and see Fri Mar 02 2018 09:00:20 GMT+0000 (GMT Standard Time), confirming its status as a string. However, when attempting this: ...

jQuery - accessing a different class within the object

Let me explain the scenario: I have a website that will delve into 4 different subjects. Initially, I have 4 divs each representing the title of those subjects. For instance, <div><p> Physics </p></div> <div><p> Chem ...

The JQuery.ajax function encountered an unexpected identifier and threw an Uncaught SyntaxError

Hey there, I'm encountering this error and I'm stumped: jQuery.ajax Uncaught SyntaxError: Unexpected identifier I'm attempting to pass some customer information to another file named "pricealarm.php" in the main directory of the FTP-Serve ...

Utilizing Laravel to Showcase Google Maps with Custom Markers Generated from MySQL Data

As I work on developing a web application that involves integrating Google Maps and multiple markers, I encountered an issue this morning. Initially, I successfully implemented the map with markers from a single database table. However, my goal now is to ...

Discover the steps to showcase a specific option from a select list at the top row through VueJs

Below is the code to iterate through the elements of teamLeaderOfWithDescendants <option :value="item.user_id" v-for="item in teamLeaderOfWithDescendants"> {{item.user_full_name}} </option> Is there a way to prioritize the row where item.u ...

Different methods to disable scrolling when the mobile menu pops up

I have implemented a mobile menu option that appears when you click on the triple line logo, but unfortunately, users can still scroll while the menu is open. I've tried using position:fixed; but haven't been successful in preventing scrolling be ...

Leveraging Angular to retrieve images from Google Feed API

I'm currently working on developing an RSS reader and trying to integrate images from the Google Feed API. While I have successfully extracted the publishedDate and contentSnippet, I am facing difficulty in getting the image src. The code snippets bel ...

Tips for displaying an alert after a successful form submission and ensuring user input validation

I created a form with PHP code to send emails, but I'm struggling to add an alert without page refresh upon submission. The alert needs to display in green or red text below the button. Validation for email input is needed, as well as protection again ...

Unable to retrieve the text enclosed between the:: before and after the:: marker

I attempted this using the XPATH finder in Chrome, and it highlighted the element. However, when running my Selenium script, I received the following error: Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: ...

Rendering with Next.js script

Within my Next.js project, there is a script implemented to render a widget. The code for this script looks like: <a className="e-widget no-button xdga generic-loader" href="https://example" rel="no ...

Issue with hidden input field not displaying array on submission

I need assistance with adding filenames that have been uploaded to an array in a hidden input field within a form. Here's what I currently have in my form: <input type="hidden" name="myFiles[]" id="myFiles" value=""> This is how my file upload ...

Nested Ajax request fails and triggers a full page reload

My goal is to search for product information and images using a product code input on index.php. The query runs in open_first.php via an ajax post request, which works perfectly. open_first.php displays images that can be selected by clicking on them. How ...

Utilizing a distinct template with ui-router: A step-by-step guide

I am currently working on an Angular application that utilizes ui-router for view routing. Within my master template, I have all the layout elements set up, including my ui-view as shown below: <div class="content" ui-view> <div> Here are my ...

Extracting dynamic content from a webpage using Selenium with Javascript rendering capabilities

Seeking a way to extract data that populates the SVG elements on a specific page: The page seems to be driven by JavaScript, making traditional BeautifulSoup methods in Python ineffective. After inspecting the network for XHR requests, it doesn't see ...

"Php makes it easy to organize seating arrangements with drag-and-drop functionality

We are currently in the process of developing a website dedicated to bus services and booking tickets. Our main goal is to allow the administrator to easily create and modify seating arrangements through drag-and-drop functionality, including the ability t ...

Replacing the tbody element in React with centered text using inline styles ---If you want

I am working with an empty array in React that I translate into state. When the array is empty, I want to insert a text that says "no match events yet..." into a react-bootstrap Table's tbody. In the current setup, I am struggling to center the text ...

Could someone provide me with a breakdown of this code utilizing the .bind() function?

The code snippet above is from the jQuery source code and it deals with event handling. It defines an array of events, such as click, focus, blur, etc., and then adds each event to the jQuery prototype using a forEach loop. var events = ['click', ...

Using the .val method on an input element modifies the HTML content without affecting the value displayed

Currently, I am working on validating the range input type by utilizing JavaScript along with jQuery's val method. While it successfully displays the output in HTML, I encountered an issue where changes to the value are not being logged in the console ...