Array cannot read property [duplicate] - javascript

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”].

Related

Global Variable not changing value in function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a nodejs app and I am trying to pass a value called membership to a page. I initialize it and try to update its value in a function but the output doesn't change. It still outputs 0. Please I need help
app.get("/",(req,res)=>{
var membershipStrength = 0;
memberData.findAll()
.then(members =>{
// console.log(members.length);
membershipStrength = members.length;
console.log(membershipStrength);
})
.catch(err => {
console.log("Error fetching members data: ", err);
});
console.log(membershipStrength);
return res.render("index",
{
page: "Admin",
membershipStrength: membershipStrength,
// tableData : global.dataOut
}
);
});
You're calling the render function before the call to findAll completes. Thus, when your server responds to the HTTP request, it still has the original value of membershipStrength in it.
You need to put the call to render inside the then handler:
app.get("/",(req,res)=>{
var membershipStrength = 0;
return memberData.findAll()
.then(members =>{
// console.log(members.length);
membershipStrength = members.length;
console.log(membershipStrength);
return res.render("index",
{
page: "Admin",
membershipStrength: membershipStrength,
// tableData : global.dataOut
}
);
})
.catch(err => {
console.log("Error fetching members data: ", err);
});
});

How to get data from axios response [duplicate]

This question already has answers here:
javascript says JSON object property is undefined although it's not
(4 answers)
Closed 3 years ago.
Trying to make a http request with axios, then accessing some property from request. Property is undefined, although it is present
public getApiURL() {
axios.get('https://xxxxxxxxx.com/metadata.json')
.then(res => {
console.log(res.data); // {"apiUrl":"https://xxxx.com/Api"}
console.log(res.data.apiUrl); // undefined
}).catch(err => {
console.log('error', err);
})
}
Try This one
`
public getApiURL=async ()=> {
try{
let result= await axios.get('https://xxxxxxxxx.com/metadata.json')
const data = JSON.parse(result.data);
console.log(data.apiUrl);
}catch(err){
console.log(err);
}
}
`

Function returning undefined seems like console.log is running before result is returned? Promise needed? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a function in another file that I want to get the response of and then do something with that response before exiting my controller function.
Here is the code from the required file:
exports.counter = function(companyID) {
options.json.companyID = companyID
request.post('/monitorCounter', options, (error, response, body) => {
if (error) {
console.log(error);
throw error;
}
if(body.success == true) return true
});
}
Here is how I am requiring the file/function
const monitorCounter = require('../controllers/counter').counter
Then this is how I am trying to test/use it in my main controller file
let valid = monitorCounter(companyID)
console.log(`Valid: ${valid}`)
I am expecting it to return true (tested via console.log and function works as expected), but I am getting undefined.
I was thinking that I need a promise for this but was not sure how to do it with it being a different file and I'm also not up to date fully yet on promises (working on that currently)
I managed to figure out how to do the promise I needed, I had tried before but was not 'return'ing a promose and was calling resolve/reject wrong. Below is working code for this issue.
exports.counter = function(companyID) {
return new Promise((resolve, reject) => {
options.json.companyID = companyID
request.post('/monitorCounter', options, (error, response, body) => {
if (error) {
console.log(error);
throw error;
}
if(body.success == true) resolve(true)
if(body.success != true) reject(false)
});
});
}

Set data object in vuejs using axios response [duplicate]

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.

Node-fetch returns Promise { <pending> } instead of desired data [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am currently trying to fetch JSON from a website using the node-fetch module, and have made the following function:
var fetch = require("node-fetch");
function getJSON(URL) {
return fetch(URL)
.then(function(res) {
return res.json();
}).then(function(json) {
//console.log(json) logs desired data
return json;
});
}
console.log(getJson("http://api.somewebsite/some/destination")) //logs Promise { <pending> }
When this is printed to the console, I simply receive Promise { <pending> }
However, if I print the variable json to the command line from the last .then function, I get the desired JSON data. Is there any way to return that same data?
(I apologize in advance if this is just a misunderstanding issue on my part, as I am rather new to Javascript)
A JavaScript Promise is asynchronous. Your function is not.
When you print the return value of the function it will immediately return the Promise (which is still pending).
Example:
var fetch = require("node-fetch");
// Demonstational purpose, the function here is redundant
function getJSON(URL) {
return fetch(URL);
}
getJson("http://api.somewebsite/some/destination")
.then(function(res) {
return res.json();
}).then(function(json) {
console.log('Success: ', json);
})
.catch(function(error) {
console.log('Error: ', error);
});

Categories

Resources