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

Guide to retrieving the data type of a List Column using SharePoint's REST API

I am currently attempting to determine the type of columns in my SharePoint list so that I can accurately populate a form with the appropriate field types. During my research, I stumbled upon this informative article in the documentation which discusses ac ...

The issue with EJS Header and Footer not showing up on the

I am currently building a basic todo list application using EJS. However, I am encountering an issue when running it. I would like to run app.js with the header and footer in EJS, but it seems that it is not recognizing the header despite using what I beli ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...

Issues with template literals not displaying line breaks

I am working with a template literal on node8.1.2 let gameDayReport = `Next 7th Day: ${nextSeventh} ${gameHours} : ${gameMinutes} Day: ${gameDay}` When I view it in my browser, the text appears as a single line instead of retaining the line breaks. It se ...

The select2 option seems to be malfunctioning as it is not

I have implemented a dropdown using Select2. Although I am able to retrieve data from the backend and display it successfully in Select2, I'm facing an issue with certain data that contains multiple spaces between words. For example: Test&nbsp;& ...

When toggling between light and dark themes using the useMediaQuery hook, the Material-ui styling is being overridden

While working with next.js and material-ui, I encountered an issue where the theme would change based on user preference. However, when switching to light mode, the JSS Styles that I had set were being overwritten. This problem only seemed to occur in ligh ...

Is there a delay in using ngShow and ngClick for authentication in AngularJS and Firebase?

Just getting started with AngularJS and encountering an unusual issue with Firebase authentication. The basic setup displays the current user status (logged in or not) along with options to sign in and out. Oddly, when I click the Log-in button for the fi ...

Guide to setting up a TreeView with default expansion

When using a @mui TreeView, all nodes are initially collapsed by default. I am trying to figure out how to have all nodes expanded by default, but haven't been successful so far. I attempted to create a method called handleExpandAll, but it doesn&ap ...

Working with Vue's v-for directive to bind computed properties

I am inputting a set of tasks into my v-form tasks: [ { title: 'title1', description: 'task 1 description', isComplete: functionA() }, { title: 'title2', ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Assistance requested with Javascript for an HTML dropdown menu

My question involves utilizing two HTML drop down menus. <select> <option value="">Please Select</option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option ...

Create the key's value in a dynamic manner within localforage

When utilizing localForage to store data offline, I encountered an issue with generating unique key values for each form submission. My goal is to have the key value generated dynamically as 'activity_1', 'activity_2', 'activity_3& ...

Utilizing Jquery select2 to enhance user experience by organizing JSON data with optgroup and

Currently, I am working with select2 in conjunction with spring mvc. The data I need to display is retrieved from my controller and should be displayed as options. However, I would like these options to be grouped within optgroups while also incorporating ...

The exception handling in Vue JS (router.beforeEach) encountered an issue while trying to convert the exception

I'm currently utilizing router.beforeEach in conjunction with localStorage. The goal is to bypass the homepage if there is data stored in localStorage, and only enter the homepage if there is no data present. Although I can successfully print the data ...

Guide to activating a CSS attribute for the AJAX tab panel with the use of JavaScript

Currently, I am utilizing the ASP.NET AJAX Tab Container with two tab panels. Each tab panel contains a div tag, and by default, my ActiveTabIndex is set to "0." Now, I am trying to apply CSS properties to the div tags using JavaScript without causing any ...

What are the potential drawbacks of relying heavily on socket.io for handling most requests versus using it primarily for pushing data to clients?

Is it advisable to switch AJAX routes (called with $.Ajax in jquery) like: GET /animals GET /animals/[id] POST /animals To socket.io events (event bound on client and server for client response): emit("animals:read") emit("animals:read", {id:asdasd}) ...

Dynamic Selection List Population in jqGrid

Using jqGrid 4.13.3 - free jqGrid In the Add form, there is a static input element and a select list element. The keyup ajax function is bound to the input element using dataEvents in the beforeInitData event. Once the Add form is displayed, entering a va ...

Guide on how to clear and upload personalized information to Stormpath

After receiving JSON data from my client, I am looking to store it in Stormpath's custom data using node.js with express.js: I have set up a basic post route: app.post('/post', stormpath.loginRequired, function(req, res){ var data = req.b ...

Updating Vue.js template data

Here is the code snippet I am working with: Vue.component('greeting', { template: `<h1>{{ greeting }}</h1>`, data: function () { return { greeting: app.text } }, }); var app = new Vue({ e ...

What is the best way to extract only the unique tags from an array using lodash?

Utilizing Vuejs and lodash, I am attempting to retrieve all unique tags for questions in my simple question "app". However, lodash is returning all tags instead of just the unique ones. Below is how I have structured the array of questions and tags: creat ...