What is the correct way to assign the products variable to the array retrieved from the API response?

I am currently trying to implement a primeblocks component and I am struggling with v-binding the dataTable to the response I receive from my API.

My issue lies in the fact that when I console.log(productData), I am getting an array that contains another array of all my products fetched from the API, instead of a regular array.

<template>
    <div>
        <DataTable :value="productData" responsiveLayout="scroll">
            <Column field="SKU" header="Code"></Column>
            <Column field="name" header="Name"></Column>
            <Column field="brand" header="Brand"></Column>
            <Column field="color" header="Color"></Column>
        </DataTable>
    </div>
</template>

<script>
import axios from 'axios';

let productData = [];

export default {
    data() {
        return {
            productData: null
        }
    },
    mounted() {
    
        const loadProducts = async () => {
          const response = await axios.get("http://localhost:1337/products")
          productData.value = response.data.products;
        };
        loadProducts()
    },
    console.log(productData)
}
</script>

Below is the console.log output:

[]
value: (87) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
length: 0
[[Prototype]]: Array(0)

It is clear that I am making a mistake somewhere. Any guidance or advice on how to correct this issue would be greatly appreciated.

Answer №1

It appears that you are logging data outside of the component while it is being parsed. Consider logging inside the loadProducts function, right after awaiting the response.

Furthermore, the productData is not reactive. To make it reactive, consider assigning it like this:

this.productData = response.data.products
. It seems that the external productData is not needed based on the information provided.

Below is a modified version of your component using the Options API:

<template>
  <DataTable :value="products" responsiveLayout="scroll">
    <Column v-for="col in columns" :key="col.field" v-bind="col" />
  </DataTable>
</template>

<script>
import axios from 'axios';

export default {
  data: () => ({
    products: [],
    columns: [
     { field: 'SKU', header: 'Code' },
     { field: 'name', header: 'Name' },
     { field: 'brand', header: 'Brand' },
     { field: 'color', header: 'Color' }
    ]
  }),
  mounted() {
    axios.get("http://localhost:1337/products")
      .then(({ data }) => this.products = data?.products || [])
  }
}
</script>

Answer №2

There's no need to use the loadProducts function in this scenario. You can achieve the same result using the .then keyword, which is more concise and asynchronous:

axios.get("http://localhost:1337/products").then(res=>{
   this.productData = res.data.products;
})

Additionally, it's recommended to use [] instead of null when declaring data properties in Vue/Nuxt.

Cheers!

Answer №3

This code snippet is essential:

productData.push(...response.data.products)

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 final child element is null when using lastElementChild

For my current Javascript project, I am tackling the task of dividing the page into two separate div elements. The left div is populated with randomly positioned images, and then I utilized the .cloneNode() method to duplicate this on the right side, exclu ...

Constructing a Laravel multi-page application using Blade, while integrating Vue.js into select pages

Currently, I am working on a traditional MPA website using Laravel and Blade templates. However, to enhance the user experience on certain pages, I want to incorporate some interactivity by integrating the Vue framework. Although I have been successful in ...

Is there a way to cross-reference a city obtained from geolocation with the cities stored in my database, and if a match is found, send the corresponding ID

Here's the script I'm currently working with: <script type="text/javascript"> search = new Vue({ el: '#offers', data: { data: [], authType: '{{uid}}', key : '1', wi ...

Exploring the concepts of AngularJS directives and resources

I've been experimenting with angularjs and rest service calls to display specific data sets, but I'm encountering challenges with custom directives and resources. Currently, I have a custom directive that loads a list of comments in an applicati ...

Number input in JavaScript being disrupted by stray commas

On my webpage, there are elements that users can control. One of these is a text input field for numbers. When users enter digits like 9000, everything functions correctly. However, if they use comma notation such as 9,000, JavaScript doesn't recogniz ...

Check for mobile browser without having to refresh the page

Currently, I am facing an issue with closing the sidebar when the user clicks on Click Me button in mobile view using flexbox layout. The problem arises because the page needs to be refreshed for it to recognize if it's in mobile mode or not by utiliz ...

a JavaScript file containing only a require statement with a list of dependencies and a function

I have a question regarding the implementation of the "require" statement in JavaScript. I am just starting to work with JS and Dojo, and I encountered an issue while developing a Plug-in for a website. The main Java class of the plugin makes a reference t ...

Implement pagination for an array in JavaScript

I am seeking a solution involving displaying a JavaScript object in a paged format. For instance, given the sample object below, I aim to present it as pages based on the value stored in the perPage variable. { "fruits":[ { "from":"Shanghai ...

Numerous Fascinating Challenges with React Native

Looking to share my React Native project and seeking help with some issues I'm facing. Despite multiple attempts, I have been unsuccessful in resolving them. Can anyone provide assistance? I have thoroughly searched Stack Overflow for similar questio ...

Verify if a certain value exists in an array while using ng-if inside ng-repeat

Currently, I have a loop using ng-repeat that goes through a list of wines obtained from an API. Alongside this, there is an array variable containing all the IDs of wines that have been marked as favorites and retrieved from the database. My goal is to sh ...

Accessing User Input Data with JQuery

Can someone help me figure out how to store the input value from a Materialize select form in HTML using a variable in javascript/jquery? Here is the HTML code for the form: <div class="input-field col s12"> <select> <option va ...

quickest method for attaching a click listener to dynamically added elements in the document object model

When adding multiple elements to the DOM, how can we ensure that these elements also have a click handler attached to them? For instance, if there is a click handler on all elements with the "canvas-section" class, and new "canvas-section" elements are con ...

Braintree drop-in feature now allows for automatic disabling of the submit button while the transaction

I've been struggling with a seemingly simple task that I just can't seem to figure out. I'm using Braintree's dropin UI and I have a submit button that I need to disable while the processing is happening, but I can't seem to find t ...

What sets the Event and EventHandler apart from each other in terms of functionality?

I am posting this question to gain clarity on the fundamental distinctions and practical applications of the Event versus EvenHandler. ...

Tips for creating a div element that closes on the second click:

On the PC version, I have three blocks that open and close perfectly when clicked. However, on the mobile version, when I click on one block, it opens but does not close unless I click on another block. Additionally, if I click again on the same block th ...

Issues with LocalStrategy not executing in passport authentication

I am currently facing an issue with authenticating using Passport and LocalStrategy. It seems like the strategy is not being called and when I log the user object in passport.authenticate, it returns "false". Below is my client-side code: logIn = () =& ...

Encountered a setback while trying to add information to a MySql database through Express

When I try to execute an insert query on a database, it throws the following error: code: 'ER_PARSE_ERROR', errno: 1064, sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versio ...

Having difficulty accessing a function within the SignalR connection function

I am currently facing an issue while trying to access a specific function within a SignalR connection function. Below is the code snippet showcasing the entire script for better understanding: $(function() { var chat = $.connection.chatHub; chat.c ...

Tips for identifying the version of a package that is installed using a package-lock.json file containing lockfileVersion = 3

After upgrading from Node 16 (npm 8) to Node 18 (npm 9), I noticed a difference in the structure of the package-lock.json files. Files generated with npm 8 have a lockfileVersion: 2, while those generated with npm 9 have a lockfileVersion: 3. The changes a ...

I'm having trouble keeping my navbar fixed

Having trouble keeping my navigation bar fixed I attempted using the <nav class="fixed-nav-bar> with no success. I also tried adjusting it in CSS, but it still wouldn't stay fixed. <nav role="navigation" class="navbar navbar-default"> ...