I'm fresh in Vue so this question can be dumb. I want to display data in Vue from my backend Rails API. The data should shows up each time a user enters the site. To do so I'm calling GET endpoint which is located below:
imports.js
const fetchSyncedProductsResultRequest = (self) => {
const jwtToken = self.$store.state.idToken;
return axios
.get(`/api/v1/imports/products/sync_result`, {
headers: {
Authorization: `Bearer ${jwtToken}`,
}
})
.then(response => {
self.unsyncedProducts = response.data['products']
})
};
export {
fetchSyncedProductsResultRequest
};
Expected JSON response from this GET will be:
{:products=>
[{:id=>"611ea9a7392ab50013cf4713", :name=>"2-Tone Hoodie", :code=>"SS22CH013", :result=>nil, :last_sync_at=>nil},
{:id=>"60ec84062f25d400150b351c", :name=>"5-Pocket Denim", :code=>"SS22WP014", :result=>nil, :last_sync_at=>nil},
{:id=>"61966dc83e81dd001731ccd7", :name=>"Zip Shirt Jacket", :code=>"FW22WT001", :result=>nil, :last_sync_at=>nil},
{:id=>"61d5cab6b41408001b0e9376", :name=>"Yankees Satin Varsity Jacket", :code=>"FW22WJ021", :result=>nil, :last_sync_at=>nil}]}
Inside my Vue file I've got:
sync_products.vue
<template>
<div>
<div >
<div >
<h4>Synchronize products</h4>
<div v-for="product in fetchedProductSyncStatus" :key="product" >
{{product}}
</div>
</div>
</div>
</div>
</template>
<script>
import {
fetchUnsyncedProductsRequest,
} from '../../api/imports'
export default {
name: 'BackboneSyncProducts',
data(){
return{
fetchedProductSyncStatus: []
}
},
}
</script>
<style scoped>
</style>
Looks like request is not sent because nothing shows up and I don't see it in Network tab. What determines the sending of this request?
CodePudding user response:
You need to hook the fetchUnsyncedProductsRequest function to Vue's lifecycles, like created or mounted. See: https://vuejs.org/guide/essentials/lifecycle.html
I would also change the function to just return the data.
const fetchSyncedProductsResultRequest = (token) => {
return axios
.get(`/api/v1/imports/products/sync_result`, {
headers: {
Authorization: `Bearer ${token}`,
}
})
.then(response => {
return response.data['products']
})
};
export {
fetchSyncedProductsResultRequest
};
Then add the created hook and add the response to fetchedProductSyncStatus
export default {
name: 'BackboneSyncProducts',
data() {
return{
fetchedProductSyncStatus: []
}
},
created () {
const jwtToken = this.$store.state.idToken;
fetchUnsyncedProductsRequest(jwtToken).then(data => {
this.fetchedProductSyncStatus = data
})
}
}
Edit: Fixed the self reference error you commented about. On that note it is bad practice to store token in the client like a store