p {{ points.returnPoints }}
returns in my html
[ { "description": null, "id": "ade5e33e-658f-4a9d-84f9-590357600054", "name": "Starting Point", "position": { "lat": -0.00027894973753803614, "lon": -0.01857362687587738 }, "radius": 100, "sort": 0 } ]
but, whenever I do on my button v-if="points.returnPoints[0].name != Starting Point`"
I am getting this error Uncaught (in promise) TypeError: Cannot read property 'name' of undefined
Why am I getting this error? I must hide visibility of my item, based on first array element's name and I am not able to do it because of this error. How do I fix this?
In my component I am calling GET request for the pointList array.
My getter:
getters: {
returnPoints(state) {
let sortState = [...state.pointList.collection]
return sortState.sort((a,b) => a.sort - b.sort)
},
}
Cannot read property of undefined after fetching data?
In fact, it happens before the data is fetched, because the data is not present when the component gets rendered: points.returnPoints[0] is undefined and trying to access the name property results in an error.
Try this instead:
<div v-if="points.returnPoints.length && points.returnPoints[0].name !== 'Starting Point'"> ... </div>
The code above assumes that points.returnPoints is an array. If it's empty, the second condition won't be checked and it won't result in an error.
Related
i'm trying to get data from db and show it on the screen. I get the data using axios, i got the response successfully. So, i use forEach to get arrays inside the data.
mounted(){
axios.get('/api/tree').then(Response => {
var datas =Response.data.trees
datas.forEach(function(data){
var tree = data.tree
console.log(tree)
console.log(tree.nodes)
})
})
}
the data is as below.
{
'id' : "aeENkvQdx",
'tree': {
'nodes' : [{ 'node_id': 0, 'text': 'test'}, .....],
'edges' : [{ 'node_id': 0, 'text': 'test'}, .....]
}
}
so, when i print console.log(tree) it's working fine. It shows { 'nodes' : [...,..,], 'edges: [...,...,...]}.
However, when i print console.log(tree.nodes) or console.log(tree.edges), then it shows an error saying
TypeError: Cannot read properties of undefined (reading 'nodes') or 'edges', even though it prints the values of nodes or edges array in the console.
I have no idea why it only causes error when i try to access nodes or edges, and how to solve this issue...
It is happening because in some of the data objects, tree property is missing. Hence, when you trying to access nodes or edges objects it is giving you the below error.
TypeError: Cannot read properties of undefined (reading 'nodes')
TypeError: Cannot read properties of undefined (reading 'edges')
You can resolve this by using Optional Chaining (?.) operator.
console.log(tree?.nodes)
console.log(tree?.edges)
Live Demo :
const datas = [{
'id' : "aeENkvQdx",
'tree': {
'nodes' : [{ 'node_id': 0, 'text': 'test'}],
'edges' : [{ 'node_id': 0, 'text': 'test'}]
}
}, {
'id' : "aeENkdYJh"
}];
datas.forEach(function(data) {
var tree = data.tree;
console.log(tree);
console.log(tree?.nodes);
});
I'm fetching data from a local server, I want to put the response into images so I can render those urls afterwards
const [images, setImages] = useState([])
useFocusEffect(
React.useCallback(()=>{
let id = '62432174021cfe441eb49bf7'
findImages(id)
.then(res=>{
console.log(res.content)
setImages(res.content)
console.log(images)
})
},[])
)//useEffect
you see that console.log(res.content) ? it shows in console the following:
Array [
Object {
"__v": 0,
"_id": "6243499ae6b17dc7de44fb0c",
"chapterid": "62432174021cfe441eb49bf7",
"url": "https://firebasestorage...",
},
Object {
"__v": 0,
"_id": "624349b0e6b17dc7de44fb0e",
"chapterid": "62432174021cfe441eb49bf7",
"url": "https://firebasestorage...",
},
Object {
"__v": 0,
"_id": "624349b7e6b17dc7de44fb10",
"chapterid": "62432174021cfe441eb49bf7",
"url": "https://firebasestorage...",
},
Object {
"__v": 0,
"_id": "624349bde6b17dc7de44fb12",
"chapterid": "62432174021cfe441eb49bf7",
"url": "https://firebasestorage...",
},
]
And you see that console.log(images) ? it's placed 2 lines after and it shows in console the following: Array [], So I'm getting a proper response from the server but when I try to put it into the useState variable it doesn't work, the funny thing is that when I Ctrl + S the project then console.log(images) gets the same display in the console as console.log(res.content), which is what I want to happen without having to save the project.
I need that image to set the res.content from the start, I watched this video https://www.youtube.com/watch?v=HvM9Ob4CHa0 the boy is doing the same as me but it works for him, look in the min 1:45, line: 30, I don't know what's going on.
this is an interesting thread that I found Why is useState() not setting the default value? but I dont't think it's the same as my scenario, I think.
The setState function of useState is async. Logging the state right after setting it, won't show the value you have just set.
However, it is guaranteed by the framework that the new value will be available in the next render cycle.
You can test this by logging the state images outside of the useFocusEffect.
const [images, setImages] = useState([])
useFocusEffect(
React.useCallback(()=>{
let id = '62432174021cfe441eb49bf7'
findImages(id)
.then(res=>{
console.log(res.content)
setImages(res.content)
})
},[])
console.log(images)
You will notie two log messages. One with an empty array. After the state changes via setImages, you will see a second console.log due to a rerender. This time with the previously set value.
I have the following JSON:
{
"data": [
{
"title": "a title here",
"news_url": "https://someurl",
"sentiment": "Neutral",
"type": "Article"
},
{
"title": "a title here",
"news_url": "https://someurl",
"sentiment": "Negative",
"type": "Article"
},
{
"title": "a title here",
"news_url": "https://someurl",
"sentiment": "Neutral",
"type": "Article"
}
]
}
I have defined my data object 'news' like so:
data() {
return {
news: [],
};
},
Now I am trying to v-for through these values so that I can get 3 divs each with the title value.
I am trying the following but I really don;t have much of a clue:
<div v-for = "title in news">
{{ title }}
</div>
I get the error: Elements in iteration expect to have 'v-bind:key' directives.
Any idea what I am doing wrong?
Thanks!
Vue documentation indicate:
It is recommended to provide a key attribute with v-for whenever
possible, unless the iterated DOM content is simple, or you are
intentionally relying on the default behavior for performance gains.
Since it’s a generic mechanism for Vue to identify nodes, the key also
has other uses that are not specifically tied to v-for, as we will see
later in the guide.
Don’t use non-primitive values like objects and arrays as v-for keys.
Use string or numeric values instead.
Then you should use the key directive binding it with string or numeric value like this:
<div v-for = "(title, index) in news" :key="index">
{{ title }}
</div>
I am using vuetify and an I'm trying to populate a select box...
...using this JSON Object:
[
{
"configurator": {
"group": {
"property": [
{
"id": "STATUS",
"value": [
{
"id": "OK",
"text": "OK"
},
{
"id": "NOK",
"text": "not OK",
"selected": "true"
}
]
}
]
}
}
}
]
...and I'm trying to render this component:
<v-list v-for="(item, i) in jsonObjPruef.configurator.group.property" :key="i">
<v-select
v-model="item.value"
:items="item.value"
:label="item.text"
/>
</v-list>
Page loads without warnings and errors and I can select from the expected values ("OK", "not OK").
While choosing e.g. "OK" the following warning is displayed:
[Vue warn]: Invalid prop: type check failed for prop "items". Expected Array, got String with value "OK".
And now if I'm trying to select again I only can pick the value I chose before ("OK").
The select option entries are only shown on the first select attempt.
Any idea what I'm missing here?
tl;dr: v-model means: "where user selection is saved". If you save it over the same exact property which holds your options, the options are gone and the <v-select> is broken.
v-model replaces jsonObjPruef.configurator.group.property with the selected option, when you select it. Which makes the <v-select> no longer have items.
You should specify a different v-model - a model property in which you store the selection, (i.e: results):
<v-list v-for="(item, i) in jsonObjPruef.configurator.group.property" :key="i">
<v-select
v-model="results[i]"
:items="item.value"
:label="item.text"
/>
</v-list>
In data, you need to initialize results : {}.
Now results will hold the selected results and you can place a watcher on it to trigger additional functionality when it changes. It doesn't have to be an object, it could be an array. It depends on what you currently have.
Obviously, you can rename results to something less generic, which makes more sense in your specific example.
If you need more help, please add a mcve.
I am new to the entire node technology stack and trying to improve myself by taking on a project. At this point I have had moderate success (possibly by chance), but I am currently stuck. My client side is using 'axios, vue, vue-router, vuetify' and a few others. The server side code is 'axios, bluebird, sequelize and sqlite3'.
My issue is as follows, I am trying to populate a 'v-data-table' by making the following function call:
<v-data-table
:headers="task_headers"
:items="getTasks(props.item.upgrade_id)"
hide-actions
item-key="task_id"
>
My function looks as follows:
methods: {
async getTasks (id) {
try {
console.log('JAC in getTask value of id is: ', id)
this.tasks = await TasksService.show(id)
console.log('JAC value of this.tasks is typeof: ', typeof this.tasks)
console.log('JAC value of this.tasks values are: ', Object.values(this.tasks))
console.log('JAC value of this.tasks keys are: ', Object.keys(this.tasks))
return this.tasks.data
} catch (err) {
console.log(err)
}
}
My debug messages produce the following output:
JAC value of this.tasks is typeof: object
JAC value of this.tasks values are:
(6) [Array(9), 200, "OK", {…}, {…}, XMLHttpRequest]0:
JAC value of this.tasks keys are:
(6) ["data", "status", "statusText", "headers", "config", "request"]
this.tasks values Array of 9 is carrying the data returned from the db that I need, but I do not understand how to return the data. I have many other service calls to the backend which are working just fine. v-data-table is expecting an array and I do not understand what I am missing to get this to work.
async getTasks (id) { <- remove async, and return an array
You are expecting in v-data-table an array and with the async property, it will return a promise therefore you got that error.
If you dont want to remove that, you can do something like this.
getTasks(props.item.upgrade_id).then((data) => {
this.tasks = data;
})
<v-data-table
:headers="task_headers"
:items="tasks"<- updated this line and no longer it will return a promisa
hide-actions
item-key="task_id"
>