Unable to access nested elements and to apply functions in Vue template? - javascript

I'm new to web development and I'm running into an issue I can't solve...
I'm using Vuejs, Express, MongoDB and Fetch API...
In my script I'm fetching data from my local server:
mounted() {
fetch("http://localhost:5000/api/" + this.$route.params.id)
.then((res) => res.json())
.then((data) => {
this.data = data
console.log(this.data.telegram.length)
})
.catch((err) => console.log(err.message))
}
console.log is working fine.
data is returned like that:
{ "_id": "6061ee831114fc4c211678e6", "path": "mypath", "telegram": [ { "date": "2021-03-21T22:00:00.708Z", "followers": 2188 }, { "date": "2021-03-22T18:40:04.751Z", "followers": 2195 } ], "__v": 0 }
Then data is stored as:
data() {
return {
data: []
}
}
First of all, I'm surprised by the format of my data. I believed it was going to appear as JavaScript Format, meaning without quotes (" ") on keys... I tried to JSON.parse the response but it returns an error like if it was already parsed. Is it normal ?
Also, in my template, I'm unable to access properties of this 'data'.
For example:
<p>{{data.telegram[0]}}</p>
or
<p>{{data.telegram.length}}</p>
is returning 'Uncaught (in promise) TypeError: Cannot read property '0' of undefined' and 'Uncaught (in promise) TypeError: Cannot read property 'length' of undefined'.
It seems there is something I have not quite understood...
Any help appreciated !

data.telegram is undefined until your mounted method get a response from the server. I suggest you to replace your template code with a computed property that check if your data has value:
<template>
<p>{{mydata}}</p>
<p>{{telegramLen}}</p>
</template>
<script>
export default {
computed: {
mydata() {
if (this.data != [])
return this.data.telegram[0]
return "No data"
},
telegramLen() {
if (this.data.length > 0)
return this.data.telegram.length
return 0
}
}
}
</script>

Related

How to get array length in vuejs

This is my script tag
<script>
export default {
data() {
return {
blogs: [],
};
},
created() {
this.paginate_total = this.blogs.length / this.paginate;
},
};
</script>
these the response I get in my console
{
"blogs": [
{
"_id": "63243272c988e721db51de9c",
},
{
"_id": "63243cb8a8189f8080411e65",
},
]
}
error i get in my console
Cannot read properties of undefined (reading 'length')
Please what I'm I doing wrong
Place this line in mounted instead of created
this.paginate_total = this.blogs.length / this.paginate;
because this blog is not available in created yet that's why it is undefined.
You can't access the object array length in mounted or created lifecycles so I just used watch property to get the object length
watch: {
blogs(blogs) {
this.paginate_total = blogs.length / this.paginate;
}
}
For row counts (as for table pagination etc.) i would use a computed property like:
computed: {
paginate_total() {
return this.blogs.length;
},
}

On page refresh the nested JSON object is throwing error while computing

const { trips, loading} = useContext(TripContext);
trips:[
{
"tripMetaData": {
"dispatchTareWt": "321",
"dispatchGrossWt": "21213",
},
"createdAt": "2021-04-14 12:07:00"
},
{
"tripMetaData": {
"dispatchTareWt": "11",
"dispatchGrossWt": "33",
},
"createdAt": "2021-04-14 11:38:27"
},
]
function getjson(){
if (trips.length && !loading){
let res = Object.values(trips.reduce((acc,curr)=>
{(acc[moment(curr.createdAt).format('DD/MM/YYYY')] = acc[moment(curr.createdAt).format('DD/MM/YYYY')] || {name: moment(curr.createdAt).format('DD/MM/YYYY'), value: 0}).value += (parseInt(curr.tripMetaData.dispatchGrossWt)-parseInt(curr.tripMetaData.dispatchTareWt));
return acc;}, {}));
return res;
}
}
I have this JSON object trips which I am getting it from a context object and a getjson function. Problem is when I am refreshing my react page it throws "TypeError: Cannot read property 'dispatchGrossWt' of undefined". Normally on page load this works fine but problem occurs on page refresh. I tried
return (
trips.length && !loading &&
<> my components here </>
but this approach is not working aswell
trips.map(()=>trips.tripMetaData).length is not the proper way to get the number of trips. trips is already a table, so you can apply the length property directly on it: trips.length.
Then, if you want to work on each trip, you can do:
trips.map(trip => trip.tripMetaData); // This will return the detail of each trip.

Show length of data array in VueJS after getting the data from API

I'm using Vue JS to get some data from an API. I want to get the length of this array and log to console via a method.
But it always logs the value of "0" instead of the real length.
I can access the data in the html without any problem and show the length ( {{ termine.length }} ).
But I want to do it using the method "logToConsole".
It seems to be a problem to access the data (which seems to be undefined in the moment of function call).
I fetch the data on "created", and output the length in "mounted", so it should be available (?).
Do you have any idea why I cannot access the data of the array in my "mounted" function, even after getting the data in "created"?
new Vue ({
el: "#calendar",
data: {
termine: [],
},
},
created() {
fetch("https://www.myurl.com/data/?json&function=GetEvents")
.then(response => response.json())
.then((data) => {
this.termine = data;
})
},
mounted() {
this.logToConsole();
},
methods: {
logToConsole: function () {
console.log(this.termine.length);
},
},
})
Of course, created hook is triggered before mounted.
But you know, you are setting termine property using API response and it is happen with async.
If you simple set termine property with simple statement like this.termine = ['a', 'b'], it will logs 2.
If you want log the data after getting the value using API, you could use watch.
like:
watch: {
termine(val) {
console.log(val)
}
}

Getting undefined trying to get value of JSON

I'm getting undefined trying to access some key inside of my JSON. The issue is because my value is inside of an Array.
I'm using console.log(jsonTest.data.eventHeader.id)
I've tried to use console.log(jsonTest.data[].eventHeader.id)
JSON Structure:
{ "data": [ { "eventHeader": { "id": "value" } } ] }
NodeJs code:
return rp(dataQuery) // simple query
.then((responseQuery: string) => {
JSON.parse(responseQuery);
const jsonTest: any = JSON.parse(responseQuery);
console.log(jsonTest.data.eventHeader.id)
fs.writeFileSync('liferaft-properties', jsonTest.username);
return responseQuery;
});
console.log(jsonTest.data[0].eventHeader.id) worked fine

React Native- Error Accessing Fetched JSON data objects

I am very new to React Native, Networking, and Programming as a whole. I am attempting to fetch JSON data from Reddit for an app I'm building, but I am receiving error messages when trying to access the Objects of the data. Below is the code I am using to fetch and console log this data.
componentDidMount(){
fetch ('https://www.reddit.com/r/financialindependence.json')
.then(res => res.json())
.then(data => {
this.setState({
data: data
})
})
.catch( error => {
console.error(error)
})
}
render() {
const myData = this.state.data
if (myData !== undefined) {
console.log(myData)
}
return(
<View style = {styles.container}>
<MainDrawerHeader title = 'Links' />
<Text> This is the Links Screen </Text>
</View>
)
}
}
This works and logs to the console the following.
[16:54:41] Object {
[16:54:41] "data": Object {
[16:54:41] "after": "t3_9ysab7",
[16:54:41] "before": null,
[16:54:41] "children": Array [
[16:54:41] Object {
[16:54:41] "data": Object {
[16:54:41] "approved_at_utc": null,
[16:54:41] "approved_by": null,
[16:54:41] "archived": true,
[16:54:41] "author": "Omitted For Privacy",
And when I access myData.data , it works as well
[16:59:29] Object {
[16:59:29] "after": "t3_9ysab7",
[16:59:29] "before": null,
[16:59:29] "children": Array [
[16:59:29] Object {
[16:59:29] "data": Object {
[16:59:29] "approved_at_utc": null,
But when I try to access the second nested object (either 'after', 'before', or 'children' (and since children is an array, I tried to access the first element) I receive the following error:
[17:00:39] TypeError: TypeError: TypeError:
undefined is not an object (evaluating 'myData.data.after')
Which confuses me because I tried to catch the undefined object with my 'if' statement. Any tips, not sure where to go from here. Thank you
I could be mistaken here, but in your third line it appears you may not be returning the res.json() to the next .then() in your Promise chain, like so:
componentDidMount(){
fetch ('https://www.reddit.com/r/financialindependence.json')
.then(res => {
let resultToPass = res.json();
return resultToPass;
})
.then(data => {
this.setState({
data: data
});
})
.catch( error => {
console.error(error)
})
}
At least superficially that would explain to me why you can access the res values and log them but they're not making it to your screen components -- they just aren't making it to where you're calling this.setState({data: data}).
Edit: I broke out the return statement by first assigning a variable, but I believe you could just as easily do return res.json(); and be fine.
Edit 2: Moved the second set of }) for the this.setState() because I made a formatting goof.

Categories

Resources