The data from the Vue.js instance is not available when accessing the Vuex store

My current task involves utilizing an API call to a django-rest backend in order to populate my data-store. The API call is functioning properly.

Upon loading index.html, I am able to inspect both store_.state.products and v.$store.state.products, which seem to contain the JSON response from the API. You can view this in the console after navigating to index.html: https://i.stack.imgur.com/X9VXx.png

and

https://i.stack.imgur.com/u5hvB.png

However, as shown by v.$data, it appears to be empty.

https://i.stack.imgur.com/bM1kl.png

Below is the code snippet for reference:

products.js

//api get call
Vue.use(VueResource)

function get(url, request) {
    return Vue.http.get(url, request)
      .then((response) => Promise.resolve(response))
      .catch((error) => Promise.reject(error))
  }

//data store
const apiRoot = 'http://127.0.0.1:8000/api/product-list/?format=json'
const store_ = new Vuex.Store({
    state: {
        products: []
    },
    mutations: {
        'GET_PRODS': function (state, response) {
            state.products = response.body;
        },
        'API_FAIL': function (state, error) {
      console.error(error)
        },
    },
    actions: {
        getProducts (store) {
            return get(apiRoot)
        .then((response) => store.commit('GET_PRODS', response))
        .catch((error) => store.commit('API_FAIL', error))

        }
    }

})

//products component
Vue.component('product', {
    template: "#product-template",
    props: ['product'],
    delimiters: ["[[","]]"],
})

//root instance
const v = new Vue({
    el: '#app',
    store: store_,
    data : function () {
      return {
        //this works fine as expected with hardcoded objects fed as data
        //products : [
        //{
        //  id:1,
        //  name:'test',
        //  brief:'descrip',
        //},
        //{
        //  id:2,
        //  name:'other',
        //  brief:'something else',
        //}
        //]
        products : this.$store.state.products
            };
    },
    delimiters: ["[[","]]"],
})

//populate store.state.products with api-call
v.$store.dispatch('getProducts')

index.html

<!DOCTYPE html>
<html>
  <head>
  {% load static %}
    <link rel="stylesheet" href="{% static '/products/bootstrap.css' %}" />
    <link rel="stylesheet" href="{% static '/products/bootstrap-theme.css' %}" />
    <link rel="stylesheet" href="{% static '/products/base.css' %}" />
    <link rel="stylesheet" href="{% static '/products/index.css' %}" />
    <link rel="shortcut icon" href="{% static '/products/favicon.ico' %}"
      type="image/x-icon" />
  </head>
  <body>

    <template id="product-template">
    <div>
        <h1>[[ product.name ]]</h1>
        <h5>[[ product.brief ]]</h5>
    </div>
    </template>

    <div id="app">
      <div class="container-fluid">
        <div class="row title-row">
          <h1 class="title">Products</h1>
        </div>
        <div class="row">
          <product v-for="product in products"  :product="product" :key="product.id"></product>
        </div>
      </div>
    </div>
    <script src="{% static "products/vue.js" %}"></script>
    <script src="{% static "products/vue-resource.js" %}"></script>
    <script src="{% static "products/vuex.js" %}"></script>
    <script src="{% static "products/products.js" %}"></script>
  </body>
</html>

Answer №1

It's possible that the variable holding products in data is initialized before the API finishes populating the store.

Consider utilizing a computed property instead. Computed properties reactively update based on their dependencies.

//root instance
const app = new Vue({
    el: '#app',
    store: myStore,
    computed: {
        products: function () {
            return this.$store.state.products;
        }
    },
    delimiters: ["[[", "]]"],
})

For proper reactivity, accessing the store with a getter method is recommended.

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

What is the rationale behind sending only one form?

Is there a way to send two forms with just one click? The first form uploads an image to the server, while the second form sends information to a database. However, only the "myform" seems to be sent. Any suggestions? <form action="uploadpic.php" met ...

Problem with Material UI Checkbox failing to switch states

I'm a bit confused about the functionality of my checkbox in Material UI. The documentation makes it seem simple, but I'm struggling to get my checkbox to toggle on or off after creating the component. const createCheckBox = (row, checkBoxStatus, ...

What methods does Angular use to handle bounded values?

Consider this straightforward Angular snippet: <input type="text" ng-model="name" /> <p>Hello {{name}}</p> When entering the text <script>document.write("Hello World!");</script>, it appears to be displayed as is without bei ...

What causes AJAX to disrupt plugins?

I am facing a challenge with my webpage that utilizes AJAX calls to load content dynamically. Unfortunately, some plugins are encountering issues when loaded asynchronously through AJAX. I have attempted to reload the JavaScript files associated with the ...

Having trouble navigating through multiple layers of nested array data in react js

I need help understanding how to efficiently map multiple nested arrays of data in a React component and then display them in a table. The table should present the following details from each collection: title, location, description, and keywords. Below ...

Do we need to use aria-labelledby if we already have label and input associated with "for" and "id"?

Here is the HTML structure for the Text Field component from Adobe Spectrum: The <label> element has a for attribute and the <input> has an id which allows screen readers to read out the label when the input is focused. So, why is aria-label ...

Using Jquery to detect if there are any Space characters in the user input

In my form, users are required to set up a new Username. The problem arises when they include a space in their username, which I want to prevent. Currently, I am able to detect the presence of a space with this code: var hasSpace = $('#usernameValue ...

Create a CSV file through an MVC Web API HttpResponse and retrieve it using AngularJS for downloading

I am attempting to create a CSV file from my web API and retrieve that file using angularjs. Below is an example of my API controller: [HttpPost] public HttpResponseMessage GenerateCSV(FieldParameters fieldParams) { var output = new byte[ ...

Stop the page from automatically scrolling to the top when the background changes

Recently, I've been experimenting with multiple div layers that have background images. I figured out a way to change the background image using the following code snippet: $("#button").click(function() { $('#div1').css("background-image ...

What is the process of directing a data stream into a function that is stored as a constant?

In the scenario I'm facing, the example provided by Google is functional but it relies on using pipe. My particular situation involves listening to a websocket that transmits packets every 20ms. However, after conducting some research, I have not foun ...

Having trouble uploading images using ReactJS on the web platform

I am currently in the process of developing a portfolio website using react js, but I'm experiencing an issue where the image I intended to display is not showing up on the live site. Despite thoroughly checking my code, I can't seem to identify ...

Loading texts with the same color code via ajax will reveal there are differences among them

I am currently designing a webshop with green as the primary color scheme. Everything is functioning perfectly, but I have noticed that the text within an ajax loaded div appears brighter than it should be. The text that loads traditionally is noticeably d ...

Tick the checkboxes that are not disabled, and leave the disabled ones unchecked

Currently, I am employing Jquery for the purpose of checking and unchecking checkboxes. However, some of these boxes are disabled, thus there is no need for them to be checked. Is there a method by which I can instruct the script to disregard disabled che ...

"Exploring the Wonders of Regular Expressions in JavaScript: Embracing the Truth and All

Hey there! I've been working on a JavaScript script to test password field validation. As of now, I have successfully made the script display an alert when the requirements are not met. However, I am now facing an issue regarding what action to take o ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

Having trouble getting a button's OnClick event to work with Bootstrap on iOS devices

Here is an example of the issue I'm experiencing: http://jsfiddle.net/d01sm5gL/2/ The onclick event functions correctly on desktop browsers, however when using iOS8, the event does not trigger. I have tried calling the function manually through the d ...

Discover the method to activate the back button feature on ajax pages

I am currently working on a website that is navigated in the following way: $(document).ready(function () { if (!$('#ajax').length) { // Checking if index.html has been loaded. If not, navigate to index.html and load the hash part with ajax. ...

The perfect approach for loading Cordova and Angularjs hybrid app flawlessly using external scripts

We have developed a single page hybrid app using cordova 3.4.0 and angularJS with the help of Hybrid app plugin(CPT2.0) in visual studio 2013. This app contains embedded resources such as jquery, angularjs, bootstrap, and some proprietary code. Additiona ...

Mobile compatibility in ECMAScript 5.1 is essential for creating seamless user

Is there a reliable source for information on ECMAScript 5.1 compatibility with mobile browser devices? ...

The content is not visible following the quotation mark

Once my script is executed, the input field ends up looking like this: <input type="text" value="How do you " /> Even if I try to escape the quotes or change them to &quot;, it still doesn't seem to work. Do you have any suggestions? $(& ...