I'm trying to access a variable inside of axios call, but it returns an undefined error. Please see my code below.
new Vue({
el: '#app',
data(){
return {
roles: [{ display: 'disp' }]
}
},
methods: {
axios.post('{{ route('role.add') }}', {
})
.then((response, roles) => {
console.log(this.roles);
})
.catch(function(err){
console.log(err);
});
}
})
Error
Undefined
Solution [SOLVED]
Added global variable above the Vue.
Try to access without this. I don't see any purpose for using this.
const axios = require("axios");
var a = "some value";
axios.get('http://www.google.com').then(function () {
console.log(a);
}).catch(e => {
console.log(e, "ERROR");
})
Just remove this keyword and it will work:
var roles = [{ display: 'disp' }];
axios.post('{{ route('role.add') }}', {
})
.then(function(response){
console.log(roles);
})
.catch(function(err){
console.log(err);
});
Or use arrow function which is not preferred:
var roles = [{ display: 'disp' }];
axios.post('{{ route('role.add') }}', {
})
.then((response, roles) => {
console.log(this.roles);
})
.catch(function(err){
console.log(err);
});
Related
I'm new to javascript and there's a problem I'm not all able to solve.
I have one array of objects, which contains 2 attributes. I want to connect the attributes, one of which will be a key and the other will be a value.
this is what I have:
[{"prefer":"code_html","rating":"5"},{"prefer":"code_css","rating":"3"}]
This is what I want to get:
[
{
"code_html": "5"
},
{
"code_css": "3"
}
]
I run this function:
const array = [{"prefer":"code_html","rating":"5"},{"prefer":"code_css","rating":"3"}]
const result = array.map(({prefer, rating}) => ({[prefer]: rating}));
console.log(result);
But I can not understand why it does not work for me.
This is the print I get, I do not understand what is wrong
[{},{},{}]
I use this code in nodeJs, maybe that's why I have a problem:
exports.addUserKmeansMatchVer2 = (req, res) => {
console.log("addUserKmeansMatch function filter:");
arr = [];
if(req.query.filterArray)
{
arr = [...req.query.filterArray];
console.log("line 256" + typeof(req.query.filterArray));
//this is print line 256object
console.log("line 257" +arr);
//this is works prints: line 257{"prefer":"sport_swimming","rating":"3"},{"prefer":"code_html","rating":"5"},{"prefer":"code_css","rating":"3"}
console.log("line 258" + req.query.filterArray);
//print exactly the same as line 257
}
let onlyPreferencesAllow = [];
arr.forEach(({prefer,rating}) => onlyPreferencesAllow.push({[prefer]: rating}));
console.log("line 262" + JSON.stringify(onlyPreferencesAllow));
//this is NOT work prints: line 262[{},{},{}]
db.doc(`/match/${req.user.handle}`)
.set("testing")
.then(() => {
return res.json({ message: "Details added successfully" });
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
}
})
})
};
I noticed that in line 257 it prints for me without the parentheses of the array without [], but in line 262 it prints with the parentheses [], I do not quite understand it
I thought of something I forgot to mention,
I get the req.query.filterArray, through the params.
Here's how I do it:
export const makeMatchVer2 = (data) => (dispatch) => {
dispatch({ type: LOADING_DATA });
axios
.get('/kmeansFilter', {
params: {
filterArray: data
}
})
.then((res) => {
dispatch({
type: MAKE_MATCH,
payload: res.data
});
})
.catch((err) => {
dispatch({
type: MAKE_MATCH,
payload: []
});
});
};
the data itself is an array, maybe here i do the mistake
The solution that worked for me:
When I send an array in params to api, I need to use JSON.stringify.
export const makeMatchVer2 = (data) => (dispatch) => {
dispatch({ type: LOADING_DATA });
axios
.get('/kmeansFilter', {
params: {
filterArray: JSON.stringify(data)
}
})
.then((res) => {
dispatch({
type: MAKE_MATCH,
payload: res.data
});
})
.catch((err) => {
dispatch({
type: MAKE_MATCH,
payload: []
});
});
};
And when I get the answer in nodeJS, I have to use JSON.parse
exports.addUserKmeansMatchVer2 = (req, res) => {
console.log("addUserKmeansMatch function filter:");
arr = [];
if(req.query.filterArray)
{
arr = JSON.parse(req.query.filterArray);
}
let onlyPreferencesAllow = [];
arr.forEach(({prefer,rating}) => onlyPreferencesAllow.push({[prefer]: rating}));
console.log("line 262" + JSON.stringify(onlyPreferencesAllow));
db.doc(`/match/${req.user.handle}`)
.set("testing")
.then(() => {
return res.json({ message: "Details added successfully" });
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
}
})
})
};
I am trying to fetch data through Axios' request and push into an array. Here is my code:
props: [
'products',
],
data: function () {
return {
algolia: '',
products_data : [],
};
},
mounted() {
this.products_data = this.products;
}
methods: {
find () {
let new_product = {};
axios.get('/product/find?barcode=' + this.barcode)
.then(function (res) {
new_product.name = resp.data.name
new_product.barcode = resp.data.barcode
new_product.unit = resp.data.unit
this.products_data.push(new_product);
})
.catch(function (err) {
console.log(err);
})
},
}
I am getting the error Cannot read property 'products_data' of undefined sue to this line this.products_data.push(new_product); I am new in Vue. Any help would be highly appreciable.
Regards
this should work, i have removed function syntax and used arrow function.
find () {
let new_product = {};
axios.get('/product/find?barcode=' + this.barcode)
.then((resp) => {
new_product.name = resp.data.name
new_product.barcode = resp.data.barcode
new_product.unit = resp.data.unit
this.products_data.push(new_product);
})
.catch((err)=> {
console.log(err);
})
}
My Vue code below loads data from a database on page load. I know how to display it in a HTML file by using simple Vue methods. However, I want to save it as a Javascript array. The Javascript array will then be fed into a map (the map requires a Javascript array). Can I do so, and if so how?
var app = new Vue({
el: '#purchase',
mounted: function() {
this.allPurchases()
},
data: {
purchases: ""
},
methods: {
allPurchases: function(){
axios.get('http://localhost:3000/')
.then(function (response) {
console.log(response);
app.purchases = response.data;
})
.catch(function (error) {
console.log(error);
});
},
},
});
You should replace app.purchases by this.purchases :
var app = new Vue({
el: '#purchase',
mounted: function() {
this.allPurchases()
},
data() {
return{
purchases: []
}
},
methods: {
allPurchases: function(){
axios.get('http://localhost:3000/')
.then( (response) =>{
console.log(response);
this.purchases = response.data;
window.purchases = response.data;//to be used globally
})
.catch(function (error) {
console.log(error);
});
},
},
});
Simply change app.purchases = to this.purchases =
I'm extremely new when it comes to using VueJS and so I am working on a small App that should list out an Authenticated person's Github repositories.
I'm having trouble when it comes to being able to access or even traverse the Array in the Picture below. I keep getting an error of undefinedif I try userRepos. Please see my code below.
I do apologize for the "Wall of Code". But I thought these javascript code snippets are the most pertinent to the issue.
This is the GitHub repo I am using as the boilerplate for this project. GitHub-Electron-Vue-OAuth
const getAxiosClient = (state) => {
return axios.create({
baseURL: state.server.url, // this is "https://api.github.com
headers: {
'Authorization': 'token ' + state.session.access_token
},
responseType: 'json'
})
}
// Mutation
[types.SET_USER_REPOS](state, repos) {
state.session.repos = repos;
},
// State Object
const state = {
server: {
url: 'http://api.github.com'
},
session: {
access_token: window.localStorage.getItem('access_token'),
ready: false,
authenticated: false,
user: {}
}
};
// Actions
export const getRepos = ({
commit,
state
}) => {
return new Promise((resolve, reject) => {
getAxiosClient(state).get('/user/repos').then(response => {
commit(types.SET_USER_REPOS, response.data)
resolve(response.data)
}, err => {
console.log(err)
reject(err)
})
})
}
export const userRepos = (state) => {
console.log(state.session.repos)
return state.session.repos;
}
<template lang="jade">
.home
span Hello {{ username }}
span {{ userRepos }}
</template>
<script>
export default {
name: 'home',
computed: {
username() {
return this.$store.getters.username;
},
userRepos() {
return this.$store.getters.userRepos;
}
},
// TODO: Push this in router
beforeRouteEnter(to, from, next) {
next(vm => {
if (!vm.$store.getters.isAuthenticated) {
vm.$router.push({
name: 'login'
});
} else {
next();
}
});
}
}
</script>
Am new to Vue.js and I would like to pass the data propert value to my template.
I have:
export default {
name: "profile",
data: () => ({
user:[]
}),
mounted() {
axios
.get('/api/user')
.then(function (response) {
this.user = response
})
.catch(function (response) {
console.error(response);
});
}
}
In the HTML template I have:
<template>
<div>{{user.name }}</div>
</template>
Now I am getting an error of
cannot set property user of undefined
A console.log(response) produces:
name: "user 1", // name exists
email ...
Try using arrow function for axios callbacks
.then((response) => {
this.user = response
})
arrow function binds the components context as you expect.
In mounted:
mounted() {
var self = this;
axios.get('/api/user')
.then(function (response) {
self.user = response
})
.catch(function (response) {
console.error(response);
});
}
}