Guidelines on populating a Vue array with data fetched from an Axios request

The v-breadcrumbs component is used to display data from the breadcrumbs array, which works seamlessly with static data.

<v-row>
    <!-- Breadcrumbs -->
    <v-col class="d-flex">
        <v-breadcrumbs :items="breadcrumbs"></v-breadcrumbs>
    </v-col>
</v-row>

<v-row>
    <v-col class="d-flex">
        <p class="blue--text title font-weight-medium my-0">{{response.products.title}}</p>
    </v-col>
</v-row>

When making a GET request using Axios to fetch product data, all works correctly as expected.

<script>
export default {
  async asyncData({$axios, params}){
    try{
      let response = await $axios.$get(`/api/products/${params.id}`)
      console.log(response);

      return{
        response: response
      }
    }catch(err){
      console.log(err);
    }
  },
  data: () => ({
    breadcrumbs: [{text: "Category", href: "index"}, {text: "", disabled: true}]
  })
</script>

The main goal is to dynamically update the last item in the breadcrumb array with data fetched from the API response.

An attempt was made to use a promise to modify the value after the GET request completes, but it resulted in crashing the app with an error: "Cannot read property 'products' of undefined", regardless of the code executed within the promise.

let response = await $axios.$get(`/api/products/${params.id}`)
                     .then((result) => {
                       // Some code here
                     })

This issue may be related to altering the 'response' value within the .then() promise. Is this the optimal solution for solving this problem, or should Vue lifecycle hooks be explored instead?

Below is an example of the API response received from the GET request:

{
  success: true,
  products: {
    rating: [],
    _id: '5e3bfd038125ebafba2ff8ce',
    owner: {
      _id: '5e397eed2da03d0817f3f870',
      name: 'Jeff Bezos',
      about: 'Jeff is the owner of this site.',
      photo: '-',
      __v: 0
    },
    category: { _id: '5e397bcc2da03d0817f3f86d', type: 'Books', __v: 0 },
    title: 'The Everything Store',
    description: 'A book about Amazon',
    photo: '-',
    price: 12,
    stockQuantity: 73,
    __v: 0
  }
}

Answer №1

To make a variable affect your DOM, you need to declare it as a property within the data function of your Vue instance:

data: () => ({
  breadcrumbs: [{text: "Category", href: "index"}, {text: "", disabled: true}],
  response: null
})

Next, to access the response data property, you can use a lifecycle hook like this:

<script>
// import axios if necessary

export default {
  data: () => ({
    breadcrumbs: [{text: "Category", href: "index"}, {text: "", disabled: true}]
  }),
  created(){
      // Ensure params object is available
      $axios.$get(`/api/products/${params.id}`)
      .then(response => {
        this.response = response;
      })
      .catch(err => {
        console.log(err);
      })
  },
</script>

Answer №2

To begin, make sure to define response in your script. This variable will then be recognized by your Vue component:

data: () => ({
  breadcrumbs: [{text: "Category", href: "index"}, {text: "", disabled: true}],
  response: {}
})

Next, assign a value to it within the then block of the axios call. This is how it operates:

$axios.$get(`/api/products/${params.id}`)
                 .then((result) => {
                   this.response = result
                 })

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

The "flickering" effect of the div is like a dance, moving gracefully between fade outs and

I am encountering a similar issue as described in this thread: same problem (fiddle: original fiddle). However, I am still learning JavaScript and struggling to apply the solution provided because my HTML code is slightly different. Can someone please assi ...

Only display entries with no content

When attempting to filter data from a search, all results are being displayed on the submit button even when entering 1, 2, or 3. Here is my code below. Please let me know if I am making a mistake somewhere. ...

What is the process for integrating a tensorflow.js model into a React-based web application?

I've been working on a React web application in Typescript that involves loading a tensorflow.js model and then applying it each time the component updates. While I successfully implemented this in a small demo app without React, I am facing some chal ...

What is the best way to increase a count in MongoDB?

I need to update the quantity count in my database every time I click a specific button. Here is the Angular directive I am using: var count = 0 $scope.postNote = function () { var deferred = $q.defer() var token = $scope.userInfo.$$state.valu ...

Problem encountered in Vue.js web application when running NPM, resulting in Error 126

When attempting to compile my Vue.js application using the command npm run prod, I encountered the following error: sh: /Users/antoinevandenheste/Downloads/magicfactory-1/node_modules/.bin/webpack: Permission denied npm ERR! code ELIFECYCLE npm ERR! errno ...

Are two JavaScript functions conflicting with each other?

Seeking assistance with integrating a Javascript/PHP/AJAX clock into my website to display various timezones (tutorial link: ) The clock implementation is functional, but it conflicts with an existing javascript stopwatch on the page, causing the clock no ...

Dim the brightness of an image on Internet Explorer

I discovered this code on another site and it functions flawlessly in Chrome and FF, however, IE (version 11.0.9) doesn't seem to like it. -webkit-filter: grayscale(0%); -moz-filter: grayscale(0%); -o-filter: grayscale(0%); filter: grayscale(0%); fil ...

I need some help with adjusting the number of rows shown per page in MaterialReactTable

I've been utilizing MaterialReactTable and my goal is to display only 5 items on each pagination page. Despite setting muiTablePaginationProps, I still see 10 items per page. How can I resolve this issue? <MaterialReactTable columns={columns} ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

What's the best way to mount a file on a field?

Can you assist in resolving this issue by utilizing a form on JSFiddle? If a user fills out the following fields: name, email, phone, message The data should be output to the console. However, if a user adds a file to the field attachment No output ...

Creating a toggle button for a div element to expand and collapse its content: Step-by-step guide

For my e-commerce site selling musical instruments, I'm designing a product landing page that showcases guitars, keyboards, violins, and cellos. As part of the design, I want to include expandable sections with detailed information about each instrume ...

VueJS Component has trouble refreshing the DOM content following an AJAX Promise

I've encountered issues updating data in my Vue application after an AJAX callback. I have previously resolved similar problems by using Vue.set, but for some reason, it's not working for me today. The only difference is that I am calling a serv ...

Restrict the input to only allow for parentheses, disallowing any letters or numerical characters

Only parentheses are allowed in the input field; letters and numbers will not be accepted. function checkBrackets() { var inputVal = document.getElementById("input").value; var result = document.getElementById("strong").value; console.log(inputVal, ...

How to dynamically add table rows and cells with JavaScript using a single selection input

I am working on a project that involves a selection input with around 5 options. Additionally, there is an empty table that follows this format: <table> <tr> <td>X (for deletion)</td> <td>Option name</td> ...

`ACCESS DENIED: Unauthorized access attempt detected in Node.js``

When attempting to connect, MySQL is establishing a connection with an unfamiliar IP address. Refer to the code below: .env MYSQL_HOST=domain.example.com MYSQL_USER=**** MYSQL_PASSWORD=**** MYSQL_DB=**** MYSQL_PORT=3306 connection.js const mysql = requir ...

Unable to perform the 'setSelectionRange' function on the 'HTMLInputElement' due to the input element's type being 'number', which does not allow selection

My attempt to enable text selection in an input box upon user click by using the code snippet below was unsuccessful: <input type="number" onclick="this.setSelectionRange(0, this.value.length)" name="quantity" /> Instead of achieving the desired ef ...

What is the best way to add table pagination at the bottom of a table?

Can someone provide guidance on implementing table pagination for the material-ui table below? The documentation is a bit unclear: <Table ria-label="a dense table"> <TableHead> <TableRow> ...

Tips for refreshing jQuery to ensure it functions smoothly for subsequent tasks

I am facing an issue with running a second process under JQuery, as shown in the code snippet below: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <script type=" ...

One function is failing to execute properly due to multiple if conditions

Take a look at my JavaScript code below: function showLater1() { if ((vidos.currentTime >= 30) && (vidos.currentTime <= 34)) { lay.style.opacity = "1"; content.style.opacity = "0"; controls.style.opacity = "0"; ...

Shader in THREE.js designed to accommodate ControlNet for normal calculations

Is there a way to adjust this standard shader to bypass the preprocessor for controlnet? Check out the code here: https://jsfiddle.net/lunchie/mpuanxL3/4/ skinnedMesh.material = new THREE.ShaderMaterial( { vertexShader: [ '# ...