I am working on an app in react that helps users new to a certain schema create queries interactively. The functionality I am currently working on is the following: anytime a relationship is deleted from the query, and fields that were accessed from that relationship should be removed as well. Assuming some users may run queries several "layers" deep, a delete on the top of the list will remove a significant amount of children, who may also have their own children. Therefore, I call the delete function recursively, checking for children, calling delete on their children first, etc etc until we return completely. The function works and hits all proper nodes (I can verify this through console logs), the issue I am having is that due to setState being asynchronous, the state only updates on the final call, and only the top node is ever actually filtered from the list. The code I am using is :
cascadeDeleteQueryFields(id) {
//loop through the array checking for anyone with parent of id^
this.state.queryFields.forEach((item) => {
if (item.parent === id) {
console.log("calling for item " + item.id);
this.cascadeDeleteQueryFields(item.id);
}
});
console.log("filtering ID : " + id);
const queryFields = this.state.queryFields.filter((c) => c.id !== id);
this.setState({ queryFields });
}
(logs currently in just for debugging purposes)
Can anyone with a little more experience with react recommend a better way to update my state so as to catch every change in the recursive call? I have looked over other questions but none of them are in a recursive function like mine and so the solutions seem like they will not work properly or be horribly inefficient.