Hello! I am searching for a user, when I find it I want to set it to config state.
Now, when I search among children arrays I got a type error saying “Cannot read property ‘children’ of undefined”. Why is it like this? How can I solve it?
I can set the config state if there is no username. Also, if I put a console.log or change something and save, I notice that the page reloads and my searched object is set even if previously it was said that Cannot read property ‘children’ of undefined.
Here the code.
const [config, setConfig] = useState({});
const makeTree = (users) => {
let tree = {children:[]};
for (const person of users) {
if (!person.report) {
tree = { ...person, ...tree };
} else {
if (tree.name === person.report) {
tree.children.push(person);
} else {
tree.children?.forEach(child => {
if (child.name === person.report) {
child.children = [];
child.children.push(person)
}
})
}
}
}
return tree;
};
const searchInChildren = (children, name) => {
for (let i = 0; i<children.length; i++) {
if (children[i]?.name === name) {
setConfig(getConfig(children[i]));
}
else if (children[i] && children[i].children && children[i].children.length > 0) {
searchInChildren(children[i].children, name)
} else {
console.log("not found!")
}
}
};
useEffect(() => {
fetch("http://localhost:4000/schema")
.then((response) => response.json())
.then((data) => {
if (username) {
const treeObj = {...makeTree(data)};
console.log("tree", treeObj);
const regex = new RegExp(username, "gi");
for (let i = 0; i < data.length; i++) {
if (regex.test(data[i].name)) {
if (treeObj.name === data[i].name) {
setConfig(getConfig(treeObj))
} else {
console.log("treeObj.children",treeObj.children, data[i] );
searchInChildren(treeObj.children, data[i].name)
}
}
}
} else {
setConfig(getConfig(makeTree(data)));
}
if(deleteSearch){
console.log("hi",deleteSearch);
setConfig(getConfig(makeTree(data)));
}
});
}, [username, deleteSearch])