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>