It works like this: I have a table made in Vue, where I have some select options. This error appears when I have a grupo (group) and this group is not associated with a maquina (machine), what shouldn't happen, the objective is that only "-" appears. Throws an error in the console and does not show in my DataTable.
The error: [/Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'id_area')
This is the part of my code that I believe is causing this error:
computed: {
linhas () {
return this.lista.map(row => {
const group = this.grupos.find(g => g.id === row.id_grupo);
const machine = this.maquinas.find(m => m.id === group.id_maquina);
const area = this.areas.find(a => a.id === machine.id_area);
return ({
href: {path: this.editRoute row.id},
cols: [
row.id,
row.tag,
row.descricao,
row.tipo === "ANALOGICA" ? "Analógica" : "Digital",
group.nome,
(machine || { nome: "-" }).nome,
(area || { nome: "-" }).nome
]
});
});
}
},
Can someone help me? I do not understand why this happening.
CodePudding user response:
The array.find() method returns undefined
if the value is not found (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
So if ther is no "machina" with the id group.id_maquina
retrieve from the previous line, the line const machine = this.maquinas.find(m => m.id === group.id_maquina);
set value undefined
to the machine
const.
And here's your error happens: reading id_area
from machine
that is undefined.
So you have to check if your variables are not undefined after array.find()
//...
const group = this.grupos.find(g => g.id === row.id_grupo);
if (group) {
const machine = this.maquinas.find(m => m.id === group.id_maquina);
if (machine) {
const area = this.areas.find(a => a.id === machine.id_area);
}
}
//...