I am new to javascript and react (16.9.0), so I hope this question is not too obvious:
I know I can make a copy of a dictionary with '...', example: const dict_new = {...dict_old} I am using this expression to avoid a referenced copy. The problem is that when I define a dictionary inside an async componentDidMount() and make a copy of it, the copy is a referenced one despite being defined correctly. Let's me show my code:
async componentDidMount() {
try {
const res1 = await fetch('/postmongo/group/');
let grupos = await res1.json();
const res2 = await fetch('/postmongo/permiso/');
const permisos = await res2.json();
const dict_permisos = {};
permisos.forEach((perm) => {
dict_permisos[perm.descripcion] = {};
grupos.forEach((gr) => {
if (gr.Permisos_gemelo.some((p) => (p.nombre === perm.nombre))) {
dict_permisos[perm.descripcion][gr.name] = true;
} else {
dict_permisos[perm.descripcion][gr.name] = false;
}
});
});
const dict_permisos_inicial = {...dict_permisos}
this.setState({
grupos,
permisos,
dict_permisos,
dict_permisos_inicial,
});
console.log(this.state);
} catch (e) {
console.log(e);
}
}
dict_permisos_inicial is referenced copy (i.e. it is changing when dict_permisos changes) and it should be independent. What am I missing? I solved by defining the dictionary twice, maybe I should build the dictionary outside the componentDidMount(), but, where?