Question:
First, let me explain what I want to do. I have tree-like data structure, with arbitrary depth from which i want to make a list of all non-leaf branches which I pass as props to Child component. Data set and recursive function are bellow.Problem: I get double data in array! I noticed that function
getBranches()
is called also in chrome VM and it just appends same data again to already existing array. See pic bellow.
Is my approach fundamentally wrong? What to do?My
getBranches()
function:My Component:
Some additional info:
branch vs leaf is distinguished by property
type
The Picture. Notice the
i
s
Answer:
I’m guessing the problem is simply that you don’t declarebranches
inside your function, making it a global variable. So the next time the function is run, you’re appending to it. Adding a const
declaration should probably do.That said, I think you can simplify
getBranches
in a clean manner:If you have better answer, please add a comment about this, thank you!