Set data object in vuejs using axios response [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I'm making an API call and getting (an expected) error back. I can console log the error message but I can not seem to set a vuejs data variable with the response. What am I doing wrong?
data: {
...
...
errors: null
},
methods: {
checkConnections: function (event) {
axios.post('/checkconnections', {
//form data is passed here
...
...
})
.then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error.response.data.error);
this.errors = error.response.data.error;
});
}
}
The console.log(error.response.data.error) part works fine but the assignment this.errors = error.response.data.error; is not. Any ideas?

The this value inside your catch handler isn't what you are expecting. The easiest way to fix that problem is to use an arrow function like .catch(error => { this.errors = error.response.data.error; }).
If your environment won't allow ES6 features, you can use Function.bind(this) instead.

Related

Javascript async function returns 'undefine' value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 28 days ago.
I am new to Javascript. I am trying to retrieve data from a MQTT broker through an async JavaScript function, querydevice. Here I am successfully getting a response from functions.logger.log(`Query msg retrived from MQTT ${msg}`) as expected.
const querydevice = async () => {
let msg;
try {
await client.subscribe("test/result");
client.on('message', function(topic, message) {
msg = message.toString();
var tp = topic.toString();
client.end();
functions.logger.log(
`Query msg retrived from MQTT ${msg}`
);
});
return {
state: msg,
}
} catch (e) {
process.exit();
}
};
I am calling the function querydevice in another function called app.onQuery as below. But I am not getting a correct response in functions.logger.log(`Device state:${dt.state}`). It shows undefined in place of the dt.state variable in the logs.
app.onQuery(async (body) => {
const dt = await querydevice();
functions.logger.log(`Device state:${dt.state}`);
return {
requestId: body.requestId,
payload: {
devices: {
"OOB-Group-7": {
on: false,
online: true
}
}
}
}
});
Can some one guide me where I am doing wrong?
I tried removing await, used .then instead in app.onQuery function. Also I tried .toString() for the dt variable.

How to call vue method inside a function within a different vue method [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
I am trying to call a Vue method called "updateUserToPremium()" within a function which is inside another vue method called testing. I'm trying to do this because 'rp' is a javascript eventhandler which is provided by a payment provider.
I've also tried with 'this.updateUserToPremium(userId)' but that does not solve the issue. I'm trying to understand the relationship between the scopes but i'm missing something.
methods: {
updateUserToPremium(userId) {
axios.post(`/user/${userId}`, {}, {
headers: { "Authorization": `Bearer ${this.$store.state.token}` }
}).then(res => {
console.log('Success session creation');
this.routeToStartpage()
}).catch(error => {
console.log(error);
return error;
})
},
testing(userId) {
var rp = new Reepay.ModalSubscription(sessionId);
rp.addEventHandler(Reepay.Event.Accept, function(data) {
console.log('Success', data);
updateUserToPremium(userId); // <--- This triggers updateUserToPremium is not defined'
rp.destroy();
})
},
}
try call method like that:
rp.addEventHandler(Reepay.Event.Accept, (data) => {
console.log('Success', data);
this.updateUserToPremium(userId); // <--- This triggers updateUserToPremium is not defined'
rp.destroy();
})

Can I populate an array with an async call from a 3rd party library inside constructor? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I have an object with an array property which I want to fill with the responses received from an asynchronous call. This call is being made by a method from a 3rd party library that receives a call back function, so I tried something like this:
class Foo {
constructor() {
this.myArray = [];
thirdPartyObject.thirdPartyMethod(
param1,
param2,
function(data){ //success callback
data.forEach(item => {
var myArrayEle = {
propertyA : item.propertyA,
propertyB : item.propertyB
};
this.myArray.push(myArrayEle);
})
},
function(data){ //error callback
throw "Error"
}
)
}
}
I get an error on this.SomeArray.push(myArrayEle); saying "cannot read property myArray of undefined" though.
I don't want to simply do stuff with the response then let it go as I want to keep this array stored so I can do stuff with it depending on what the user does instead of having to make another call later on to get the same data.
Is there a way to do this inside the constructor or do I have to use promises somewhere else to do this?
One way to handle this is to have a constructor on your class that just sets things up and a different init function that can handle getting data asynchronously and let you know when the object is properly initialized. Here's an example where we mock your thirdPartyMethod. When you call the constructor, the array will be undefined, but you can call init().then() to know when it's ready:
const thirdPartyObject = {
thirdPartyMethod(param1, param2, success, error) {
setTimeout(() => success([{propertyA: "propA0",propertyB: "propB0"}, {propertyA: "propA1",propertyB: "propB1"
}]), 1000)
}
}
class Foo {
constructor(data) {
console.log("making instance")
this.myArray = data;
}
init() {
console.log("starting init")
return new Promise((resolve, reject) => {
thirdPartyObject.thirdPartyMethod(
'param1','param2',
(data) => { //success callback // use arrow function so 'this' works
this.myArray = data.map(item => {
return {
propertyA: item.propertyA,
propertyB: item.propertyB
};
})
console.log("finished init, data ready")
resolve(true)
},
function(data) { //error callback
reject("Error")
}
)
})
}
}
let f = new Foo()
f.init()
.then(() => console.log(f.myArray))
.catch(err => console.log(err))

Array cannot read property [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
This is the problem
This is the script
var data = [];
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(function (response) {
data.push(response.data['0'])
})
.catch(function (error) {
console.log(error);
});
console.log(data);
console.log(data['0'].body); //this is where I get the error
As you can see in the picture it should be correct but why I cannot read the property ?
Are you sure the data object is filled when you try access it?
Does the following work?
var data = [];
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(function (response) {
data.push(response.data['0'])
console.log(data['0'].body);
})
.catch(function (error) {
console.log(error);
});
Your data is an array, so it must be accessed with integer like data[0].body.
String accessor might be useful for Object type, not array. For example, you can also do data[0][“body”].

Logging value from promise .then() shows data but when returning it is undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
So I have a function that uses the refresh token I have to get a new access token and I want to use this function before every call that requires an access token.
The first function refreshAccessToken() makes the request and returns the response including the body that contains the new access token. Now I thought this was enough but I was getting undefined followed by the actual data and doing some digging I found this question:
Promise returns undefined
which led me to returning the value from this function so the promise resolves fully and using it in another, returnAccessToken().
returnAccessToken() is supposed to take the resolved promise value and return the access token but it behaves unexpectedly. The console.log line works like a charm and it logs the correct value everytime but when I return the token and try to use it in the function below it, it is undefined again.
api.js
"use strict"
const request = require("request-promise-native");
refreshAccessToken: async function (credentialsObject) {
const options = {
method: "POST",
uri: <refresh token uri>,
resolveWithFullResponse: true,
json: true
};
return await request(options);
},
returnAccessToken: function (auth) {
this.refreshAccessToken(auth)
.then(function (result) {
// This logs the result correctly
console.log(result.body);
return result.body;
}, function (err) {
console.log(err);
});
},
actionRequiringAccessToken: function (auth) {
let tokens = this.returnAccessToken(auth);
// This returns undefined
console.log(tokens);
}
index.js
Also yes I realize that logging here does nothing as I don't currently return a value I just include it because this is how actionThatRequiresAccessToken() is run in my setup.
"use strict"
const api = require("api");
let auth = {
// Credentials
};
api.actionRequiringAccessToken(auth)
.then(function (data)) {
console.log(data);
}, function (err) {
console.log(err);
}
Just add return in returnAccessToken method.. you are not returning anything
returnAccessToken: function (auth) {
return this.refreshAccessToken(auth)
return result.body;
That returns the data into the .then chain. So actually your method doesnt return anything. Might add a return here:
returnAccessToken: function (auth) {
return this.refreshAccessToken(auth) /*...*0
}
I would suggest make actionRequiringAccessToken async and drop returnAccessToken
actionRequiringAccessToken: async function (auth) {
let response = await this.returnAccessToken(auth);
let tokens = response.body //parse the response... whatever returnAccessToken does
console.log(tokens);
}

Categories

Resources