How do i pass data to a function under data in vuejs - vue.js

I tried to reference this.items in the function in taskList.cls.cls
the main idea is to run a task in vue-terminal then pass the result of the post request to this.items but it's returning undefined
data() {
return {
//this is the data i want to pass the post response to
items: [],
query: '',
taskList: {
// your tasks
cls: {
description: 'Clear Terminal',
cls: this, async(pushToList) {
const p = new Promise(resolve => {
this.query = 'SELECT * FROM notifications'
const token = localStorage.getItem('token')
axios.post('/query', {'query': this.query}, {
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
}).then(res => {
//i want to reference
**this.items = res.data.data.result**
//
pushToList({type: 'system', label: 'Running query', message: 'Please wait!!'})
}).catch(err => {
console.log(err)
})
setTimeout(() => {
resolve({type: 'success', label: 'Success', message: 'Success!'})
this.test = "worked"
}, 2000)
})
return p
}
}
},
commandList: {
// your commands
}
}
},

Don't do that, call api on "mount()".

Related

Status failed error get after enter card input in network international ngenius payment in react native?

First we create sandbox account from https://www.network.ae/en/contents/listing/online-solutions#book-1
then we create access Token see code
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/vnd.ni-identity.v1+json");
myHeaders.append("Authorization", `Basic ${}API_KEY`);
myHeaders.append("Cookie", "\_abck=5C342393A623B53581D9AE558C857BF2\~-1\~YAAQfXYsMa+W3wWFAQAACGk7MwlNL93fTExvJYX4pRpd6PZpRFbRT0BgePfZ2tn15MkLCVst80XVExP/xPZkPh0LUZq4QO4k+KN0bm+Tz0NlX26lWmSlI6mq0kePXMH9MJt7yQy7Rx9ZIsR2Amcb44zP+hnySdCx2uq3vwgl4ZVMQ2soqosGNHQuESjb/JJAirysYwiyN7/Mw/qg5NzXzf2ncRTbB/3CcVp/yiZPOwAsxD8x+8oZA3VAxLgvbuv0Tn9ccNN9oPATqzDtoXD1LnQorof6S/S6btPx4BZTgFeqvmxX3q5SNSlsDgySTzI5qkp81wrjTm5ficp1U0k5fcimfaR0V8Xq21luPY9VdveWYd5B87UOIcalA2CQz2S7yFSo14uqKarLVFbh00Vd1Zw=\~-1\~-1\~-1; bm_sz=AF5FEAEE5BC3A58968E80BB8D640735E\~YAAQfXYsMbCW3wWFAQAACGk7MxLpffLMR5ZpUagjSJqRS4G5rjc8MolC2xNhZUaUKTKGMj5Fvi0eLn3cbULd/jtI4QO0h8Cl4c3bFROSPs9jpPu1UFDm9R1gGBB6T7rIFPU+sxiw2wQ7gGvrlik680yFDoUraO3MoRl8cfpOu73nyKryhpb1ebghFcrF2aYM9B4f3c8ER1Fk1VTXN5TGij9bLAT7BDjVOtLjQVG5AL/wKZ57t21EFnCqlnXioDXla8Jylj6T7EQzE/5yKno2Z9Z6jMTx1rU6Jcy5nUq6SG50aVYOUYwA/w1k6WSj\~3749186\~4343095");
var raw = "";
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://api-gateway.sandbox.ngenius-payments.com/identity/auth/access-token", requestOptions)
.then(response => response.json())
.then(result => {
setAccessToken(result.access_token)
})
.catch((e)=>console.log(e)
Then we create an order
var myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${access_token}`);
myHeaders.append("Content-Type", "application/vnd.ni-payment.v2+json");
myHeaders.append("Accept", "application/vnd.ni-payment.v2+json");
myHeaders.append("Cookie", "_abck=5C342393A623B53581D9AE558C857BF2~-1~YAAQJfhWuMbikwmFAQAAm3R2KgkBO6swEeKoHNG6113OL/hvGd9LQQEo5ieCnty0rrZ7UcaRqt7InR2UUWFze7723wDPiy+SCmtMNKKL4zCJi7fwqJed1SMa2PWjCe5qWiFf/Fa0NtMY3a7TedM+6XI3cMMieW4GMHrQwGTz0BrFsZ3gC6jCUgYUTFO55uMpD3627GjbcZmsluCPLWKVLdGlsPX/wIknh1Tl/+YSO58Bnv97KpZnb0ZLZck2PYFnzGOPTiJ2JQe6vakvSFh68UxMIZYVxekwS2LTZjJGtZqLMt45A/lLbpxq95qzzCMWdxrwE0JgMgWfgu9l1k+Scq69UpgOo331AEJ+AASZF1MZ4CRJ7MEs1WpjlTbDroZVS0Uh~-1~-1~-1");
var raw = JSON.stringify({
"action": "PURCHASE",
"amount": {
"currencyCode": "AED",
"value": 2000
},
"emailAddress": "govindsingh#gmail.com",
"merchantOrderReference":"my-order",
"billingAddress":{
"firstName":"Govind",
"lastName":"Singh",
"address1":"abc",
"city":"Dubai",
"state":"Dubai",
"countryCode":"AED"
},
"merchantAttributes":{
"skipConfirmationPage":true,
"skip3DS":true
}
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch(`https://api-gateway.sandbox.ngenius-payments.com/transactions/outlets/${Outlet_id}/orders`, requestOptions)
.then(response => response.json())
.then(result => {
setOrder(result.access_token)
})
.catch((e)=>console.log(e)
then we call make card payment function by https://www.npmjs.com/package/#network-international/react-native-ngenius
const res = await initiateCardPayment(order);
console.log("res"+ res)
Alert.alert(
'Success',
'Payment was successful',
[{ text: 'OK', onPress: () => console.log('OK Pressed') }],
{ cancelable: false },
);
} catch (err) {
console.log(err);
alert(
'Error',
'Payment was not successful',
[{ text: 'OK', onPress: () => console.log('OK Pressed') }],
{ cancelable: false },
);
}
then we get an error -
[status:failed]
Thanks in Advance
Please give me any solution

like/dislike button with api call not working using vue an mongoDB

I am learning vuejs and i am working on my first project which is a social network, and i want to implement a like button that call the api to add a like or remove it if the user has already liked it. It does work in my backend but i can't make it work in the front.
I need to send the userId and add or remove the like when i click on the button
This is the data
data() {
return {
post: {
file: "",
content: "",
likes: 0,
},
showModal: false,
showModifyPost: false,
user: {
firstname: "",
lastname: "",
_id: "",
},
};
},
the last method i tried
likePost(id) {
axios
.post('http://127.0.0.1:3000/api/post/like/' + id, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then(() => {
console.log("response", response);
this.user._id = response.data._id;
if(post.usersLiked == user._id) {
this.post.likes += 0
} else if (post.usersLiked != user._id) {
this.post.likes += 1
};
})
.catch((error) => console.log(error));
}
and this is the model
const postSchema = mongoose.Schema({
userId: { type: String, required: true, ref: "User" },
content: { type: String, required: true, trim: true },
imageUrl: { type: String, trim: true },
likes: { type: Number, default: 0 },
usersLiked: [{ type: String, ref: "User" }],
firstname: {type: String, required: true, trim: true },
lastname: {type: String, required: true, trim: true },
created_at: { type: Date},
updated_at: { type: Date }
});
Any idea what is wrong ? Thank you !
.then(() => { // you missed value response from Promise here
this.user._id = response.data._id;
if(post.usersLiked == user._id)
})
Do you mean this.post.usersLiked === user._id I suppose, so post within your data options should be
post: {
file: "",
content: "",
likes: 0,
usersLiked: false,
// something else reflect to your post schema
},
i want to implement a like button that call the api to add a like or remove it if the user has already liked it
By saying that you just need a simple boolean value to do this
likePost(id) {
axios
.post('http://127.0.0.1:3000/api/post/like/' + id, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then((response) => {
// Just need to toggle state
this.$set(this.post, 'usersLiked', this.post.usersLiked !== response?.data?._id)
})
.catch((error) => console.log(error));
}
Found the answer, i changed the axios method to this
likePost(id) {
let userId = localStorage.getItem('userId');
axios
.post('http://127.0.0.1:3000/api/post/like/' + id, { userId }, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then((response) => {
console.log(response.data);
this.getAllPost();
})
.catch((error) => console.log(error));
}
i also made a few changes to the data
data() {
return {
posts: [],
post: {
file: "",
content: "",
},
showModal: false,
showModifyPost: false,
user: {
firstname: "",
lastname: "",
_id: "",
},
};
},
and i also made some changes on the controller
exports.ratePost = (req, res, next) => {
console.log(req.body.userId)
//using findOne function to find the post
Post.findOne({ _id: req.params.id }).then(post => {
if (!post.usersLiked.includes(req.body.userId)) {
// making a object with $inc and $push methods to add a like and to add the user's id
let toChange = {
$inc: { likes: +1 },
$push: { usersLiked: req.body.userId },
};
// we update the result for the like
Post.updateOne({ _id: req.params.id }, toChange)
// then we send the result and the message
.then(post =>
res
.status(200)
.json(
{ message: "Liked !", data: post }
)
)
.catch(error => res.status(400).json({ error }));
} else if (post.usersLiked.includes(req.body.userId)) {
// using the updateOne function to update the result
Post.updateOne(
{ _id: req.params.id },
// we use a pull method to take off a like
{ $pull: { usersLiked: req.body.userId }, $inc: { likes: -1 } }
)
.then(post => {
// then we send the result and the message
res
.status(200)
.json(
{ message: "Post unliked", data: post }
);
})
.catch(error => res.status(400).json({ error }));
}
});
};

Got error 422 with vuex (dispatch) in vuejs

I got an error :
422 (Unprocessable Content)
when I tried to post a data in register form
I have this in my Register.vue
methods: {
register() {
this.$store.dispatch('register', {
firstname: this.firstname,
lastname: this.lastname,
email: this.email,
password: this.password,
});
},
},
};
and in my vuex
actions: {
register(credentials) {
const requestOptions = {
method: 'POST',
headers: { 'content-type': 'application/json' },
dataType: 'json',
body: JSON.stringify(credentials),
};
console.log(credentials);
return fetch('http://localhost/api/users', requestOptions)
.then((response) => {
return response.json;
})
.catch((err) => console.log(err.message));
},
}
Anyone know where I'm wrong ?
Many thanks
Don't return twice if the request is good.
actions: {
register(credentials) {
const requestOptions = {
method: 'POST',
headers: { 'content-type': 'application/json' },
dataType: 'json', // not needed
body: JSON.stringify(credentials),
};
console.log(credentials);
return fetch('http://localhost/api/users', requestOptions) // first time
.then((response) => {
return response.json; // second time
})
.catch((err) => console.log(err.message));
},
}
Also use async/await. I'd do
actions: {
async register(credentials) {
const requestOptions = {
method: 'POST',
headers: { 'content-type': 'application/json' },
dataType: 'json',
body: JSON.stringify(credentials),
};
const res = await fetch('http://localhost/api/users', requestOptions);
}
return res.json();
}
And in the Register.vue
methods: {
register() {
this.$store.dispatch('register', {
firstname: this.firstname,
lastname: this.lastname,
email: this.email,
password: this.password,
}).then(data => {
console.log(data)
}).catch((err) => console.log(err.message));
});
},
};
Also you can put it in try/cache etc. It's up to you.
Check the docs, it well explained.

Vuex state array turning an proxy object when it is mutated

I develop a project which gets datas from database. I use Vuex for state management.
Vuex Store File
const store = createStore({
state: {
notUser: {
name: "",
email: '',
password: ''
},
user: {
name: '',
email: '',
messages: [],
about: '',
place: '',
age: '',
role: '',
blocked: false
},
problem: {
title: '',
content: ''
},
problems: [],
errorMessage: {
error: false,
message: '',
success: false
},
},
mutations: {
errorHandler(state, error) {
state.errorMessage.error = true
state.errorMessage.message = error.response.data.message
},
defineUser(state, req) {
state.user = req.data.user
console.log(state.user)
},
getProblems(state, problems) {
state.problems = problems
console.log(state.problems)
}
},
actions: {
register({ commit }, notUser) {
axios({
method: 'post',
url: 'http://localhost:3000/api/auth/register',
data: notUser,
withCredentials: true,
headers: {
"Accept": "application/json"
}
})
.then(res => {
this.state.errorMessage.success = true
console.log(res.data.data.user)
})
.catch(err => {
this.state.errorMessage.success = false
console.log(err.response)
commit('errorHandler', err)
})
},
userLogin({commit}, notUser) {
axios({
method: 'post',
url: 'http://localhost:3000/api/auth/login',
data: notUser,
withCredentials: true,
headers: {
"Accept": "application/json"
}
})
.then(res => {
this.state.user = res.data.data.user
this.state.errorMessage.success = true
console.log(this.state.user)
})
.catch(err => {
this.state.errorMessage.success = false
console.log(err.response)
commit('errorHandler', err)
})
},
checkUser({commit}, access_token) {
axios({
method: 'post',
url: 'http://localhost:3000/api/auth/VpW02cG0W2vGeGXs8DdLIq3dQ62qMd0',
data: access_token,
withCredentials: true,
headers: {
"Accept": "application/json"
}
})
.then(res => {
console.log(res)
commit('defineUser', res)
return true
})
.catch(err => {
console.log(err.response)
commit('errorHandler', err)
return false
})
},
sendProblem({commit}, problem) {
axios({
method: 'post',
url: 'http://localhost:3000/api/problem/add',
data: problem,
withCredentials: true,
headers: {
"Accept": "application/json"
}
})
.then(res => {
console.log(res)
return true
})
.catch(err => {
console.log(err.response)
commit('errorHandler', err)
return false
})
},
getAllProblems({commit}) {
axios({
method: 'get',
url: 'http://localhost:3000/api/problem/getall',
withCredentials: true,
headers: {
"Accept": "application/json"
}
})
.then(res => {
commit('getProblems', res.data.data)
return true
})
.catch(err => {
console.log(err.response)
commit('errorHandler', err)
return false
})
}
// registerUser({commit}, user) {
// commit('register', user)
// }
},
Vue Component: Where Vuex store is being used
computed: {
...mapState(["user", 'problems'])
},
mounted() {
return this.getAll()
},
methods: {
...mapActions(['getAllProblems']),
goToAdd() {
this.$router.push('/add')
},
async getAll() {
this.getAllProblems()
}
}
The problem is when I try to request with getAllProblems action, it should mutate problems variable with getProblems(). Actually it does. But after problems variable changes, it turns something a proxy object. Here are images:
Here is an image of proxy object:
The original data coming from database:
Thanks for comment of #Hasan Hasanova
Okay got it. I called api before website is mounted and used function to get variables from store. The other problem was happened because of using wrong syntax of v-for. Here is the code:
computed: {
allProblems() { // this is the problems array that i was trying to get
return this.$store.state.allProblems
},
loader() {
return this.allProblems == null ? true : false
}
},
beforeMount() {
this.$store.dispatch('getAllProblems', {root: true})
},
And here is the template code :
<div v-if="allProblems.length > 0" class="middle-side">
<div v-for="(problem) in allProblems" :key="problem.id" class="card">
<router-link :to="{ name: 'ProblemDetail', params: { id: problem._id, slug: problem.slug }}">
<div class="card-header">
<div class="card-header-title">
<div class="user-image">
<img src="../../assets/problem.png" />
</div>
<span class="user-name">{{ problem.user.name }}</span>
</div>
...
Thanks for all.
I have the same problem as yours, but I solved it first by converting it before the getter's return, converting it to JSON to string, and converting a string to JSON again before returning it.
const str = JSON.stringify(data)
return JSON.parse(str)
You want to use mapActions to call the action. Then get your data via state, instead of returning the function, since the action is calling a mutation via commit.
computed: {
// you have access to `problems` in the template. Use `v-if` before you `v-for` over the array of problems.
...mapState(["user", 'problems'])
},
mounted() {
this.getAllProblems();
},
methods: {
// ...mapActions(['getAllProblems']),
goToAdd() {
this.$router.push('/add')
}
}
For some reason that happens during the passing of res.data.data to mutations. So if you're expecting a single row result set you should do like:
POPULATE_THIS_STATE_VAR(state, data) {
state.thisStateVar = data[0]
}
... and if you're expecting an array of objects to the result set like what you have, you could do like:
POPULATE_THIS_STATE_VAR(state, data) {
if (data) {
for (let i = 0; i < data.length; i++) {
state.thisStateVar .push(data[i])
}
}
}

VueX and axios posting previous data along with data from new request

I have a postAsset action in my vuex store like so
async postAsset({dispatch}, asset) {
const f = await dispatch('srcToFile', asset);
asset[0].files.fileList = f;
const fileData = asset[0].files.fileList;
const detailData = asset[0].detail;
const fData = new FormData();
fData.append('Name', asset[0].name);
Object.keys(detailData).forEach((key) => {
fData.append(`Detail.${key}`, detailData[key]);
});
for (var i = 0; i < fileData.length; i++) {
fData.append('Files', fileData[i]);
}
await axios({
method: 'post',
url: 'https://localhost:5001/api/Assets',
data: fData,
headers: {
'Content-Type': undefined
}
})
.then(function(response) {
console.warn(response);
})
.catch(function(response) {
console.warn(response);
});
}
It is successfully posting to my api backend and to the database.
The issue that I am running into is that after I make the first post it posts the previous data and the new data I do not know why it is doing this. I did add await to the axios call but that just slowed it down it is still posting two times after the first and im sure if i keep posting it will continue to post the previous ones into the db again and again. Im at a loss as to what is going on so reaching out for some assistance to see if I can get this resolved.
examples of what it looks like in the db
does anyone have any advice for me so I can get this fixed? I should only be getting one item posted at a time that is the desired result. I have gone through my inputs and put in .prevent to stop them from clicking twice but I don't think it is that .. this is like it is saving the data and reposting it all at once each time I add a new record .
UPDATE:
the code that calls the action
populateAssets ({ dispatch }, asset) {
return new Promise((resolve) => {
assets.forEach((asset) => {
commit('createAsset', asset);
);
dispatch('postAsset', asset);
resolve(true);
});
},
the populate assets populates a list with a completed asset.
and asset is coming from the srcToFile method
that converts the files to a blob that I can post with
async srcToFile(context, asset) {
const files = asset[0].files.fileList;
let pmsArray = [];
for (let f = 0; f < files.length; f++) {
var data = files[f].data;
let name = files[f].name;
let mimeType = files[f].type;
await fetch(data)
.then(function(res) {
const r = res.arrayBuffer();
console.warn('resource ', r);
return r;
})
.then(function(buf) {
console.warn('buffer: ', [buf]);
let file = new File([buf], name, { type: mimeType });
pmsArray.push(file);
});
}
console.warn(pmsArray);
return pmsArray;
},
asset is an array from my add asset component
structure of asset
name: '',
detail: {
category: '',
manufacturer: '',
model: '',
serialNumber: '',
purchasePlace: '',
quantity: 1,
acquiredDate: '',
purchasePrice: '',
currentValue: '',
condition: '',
assetLocation: '',
retiredDate: '',
description: ''
},
files: {
fileList: []
}
hope this helps out some
the whole store file
import Vue from 'vue'
import Vuex from 'vuex'
import { states } from '../components/enums/enums'
import { getField, updateField } from 'vuex-map-fields'
import axios from 'axios'
Vue.use(Vuex);
const inventory = {
namespaced: true,
strict: true,
state: {
assets: {
items: []
},
categories: [],
manufacturers: [],
assetLocations: [],
conditions: ['New', 'Fair', 'Good', 'Poor']
},
getters: {
assetItems: state => state.assets.items,
getAssetById: (state) => (id) => {
return state.assets.items.find(i => i.id === id);
},
conditions: (state) => state.conditions,
categories: (state) => state.categories,
manufacturers: (state) => state.manufacturers,
assetLocations: (state) => state.assetLocations
},
mutations: {
createAsset (state, assets) {
state.assets.items.push(assets);
},
createCategories (state, category) {
state.categories.push(category);
},
createManufacturers (state, manufacturer) {
state.manufacturers.push(manufacturer);
},
createLocations (state, locations) {
state.assetLocations.push(locations);
}
},
actions: {
addToCategories ({ commit }, categories) {
commit('createCategories', categories);
},
addToManufacturers ({ commit }, manufacturers) {
commit('createManufacturers', manufacturers);
},
addToLocations ({ commit }, locations) {
commit('createLocations', locations);
},
populateAssets ({ dispatch }, asset) {
//return new Promise((resolve) => {
// assets.forEach((asset) => {
// commit('createAsset', asset);
// });
dispatch('postAsset', asset);
// resolve(true);
//});
},
addAsset ({ dispatch, /*getters*/ }, newAsset) {
//let assetCount = getters.assetItems.length;
//newAsset.id = assetCount === 0
// ? 1
// : assetCount++;
dispatch('populateAssets', [newAsset]);
},
async srcToFile(context, asset) {
const files = asset[0].files.fileList;
let pmsArray = [];
for (let f = 0; f < files.length; f++) {
var data = files[f].data;
let name = files[f].name;
let mimeType = files[f].type;
await fetch(data)
.then(function(res) {
const r = res.arrayBuffer();
console.warn('resource ', r);
return r;
})
.then(function(buf) {
console.warn('buffer: ', [buf]);
let file = new File([buf], name, { type: mimeType });
pmsArray.push(file);
});
}
console.warn(pmsArray);
return pmsArray;
},
async postAsset({ dispatch }, asset) {
const f = await dispatch('srcToFile', asset);
asset[0].files.fileList = f;
const fileData = asset[0].files.fileList;
const detailData = asset[0].detail;
const fData = new FormData();
fData.append('Name', asset[0].name);
Object.keys(detailData).forEach((key) => {
fData.append(`Detail.${key}`, detailData[key]);
});
for (var i = 0; i < fileData.length; i++) {
fData.append('Files', fileData[i]);
}
await axios({
method: 'post',
url: 'https://localhost:5001/api/Assets',
data: fData,
headers: { 'Content-Type': undefined }
})
.then(function(response) {
console.warn(response);
})
.catch(function(response) {
console.warn(response);
});
}
}
};
const maintenance = {
state: {
backup: []
},
strict: true,
getters: {},
mutations: {},
actions: {}
};
const assetProcessing = {
namespaced: true,
state: {
currentAsset: {
id: 0,
name: '',
detail: {
category: '',
manufacturer: '',
model: '',
serialNumber: '',
purchasePlace: '',
quantity: 1,
acquiredDate: '',
purchasePrice: '',
currentValue: '',
condition: '',
assetLocation: '',
retiredDate: '',
description: ''
},
files: {
fileList: []
}
},
filePosition: -1,
selectedItem: -1,
state: states.view,
isNewAsset: false
},
getters: {
getField,
getOpenAsset (state) {
return state.currentAsset
},
getSelectedAsset: (state, getters, rootState, rootGetters) => (id) => {
if (state.isNewAsset) return state.currentAsset
Object.assign(state.currentAsset, JSON.parse(JSON.stringify(rootGetters['inventory/getAssetById'](!id ? 0 : id))));
return state.currentAsset
},
appState: (state) => state.state,
getCurrentPosition (state) {
return state.filePosition
},
selectedAssetId: (state) => state.selectedItem
},
mutations: {
updateField,
setAsset (state, asset) {
Object.assign(state.currentAsset, asset)
},
setFiles (state, files) {
Object.assign(state.currentAsset.files, files)
},
newAsset (state) {
Object.assign(state.isNewAsset, true)
Object.assign(state.currentAsset, {
id: 0,
name: '',
detail: {
category: '',
manufacturer: '',
model: '',
serialNumber: '',
purchasePlace: '',
quantity: 1,
acquiredDate: '',
purchasePrice: '',
currentValue: '',
condition: '',
assetLocation: '',
retiredDate: '',
description: ''
},
files: {
fileList: []
}
})
},
updateSelectedItem (state, id) {
Vue.set(state, 'selectedItem', id);
},
updateState (state, newState) {
Vue.set(state, 'state', newState);
}
},
actions: {}
};
export const store = new Vuex.Store({
modules: {
inventory: inventory,
maintenance: maintenance,
assetProcessing
}
})
add asset is called when the user clicks the save button on the form
addAsset () {
this.$store.dispatch('inventory/addAsset', this.newAsset) <--- this calls add asset
this.$store.commit('assetProcessing/updateState', states.view);<-- this closes the window
},
So after much debugging we found that the eventbus was firing multiple times causing the excessive posting we added
beforeDestroy() {
eventBus.$off('passAssetToBeSaved');
eventBus.$off('updateAddActionBar');
},
to the AssetAdd.vue component and it eliminated the excessive posting of the asset.
I want to thank #phil for helping me out in this.