i'm doing a recursive array merge into an array but it's not working
this is current data
let currentData = [
{
"id":1,
"content":"Comment 1"
"answers":[
{
"id":3,
"content":"Comment 3"
"answers":[
{
"id":4,
"content":"Comment 4",
"answers":[]
},
{
"id":5,
"content":"Comment 5",
"answers":[]
}]
}
]
}
{
"id":2,
"contents":"Comment 2"
"answers":[
{
"id"6,
"content":"Comment 6",
"answers":[]
}
]
}
]
I want like this
[
{
"id": 1,
"content": "Comment 1"
},
{
"id": 2,
"content": "comment 2"
},
{
"id:": 3,
"content": "comment 3"
},...
]
I tried using this function but it doesn't work
const [replyList, setReplyList] = useState([])
useEffect(()=>{
handleMerge(currentData)
},[])
const handleMerge = (reply) => {
if (reply.length == 0) {
return
}
for (let i = 0; i < reply.length; i++) {
setReplyList([...replyList,reply[i]])
handleMerge(reply[i].reply)
}
}
Top comments (1)
do not use setReplyList in a loop, because it is async, it's not guaranteed to change its data immediately.
write a method that takes an array like the first one and returns the desired array, and then setReplyList(result)
Another option maybe useMemo. You can use useMemo that depends on the first array structure and then returns the second one