How to use data hooks to populate the total item counts in the reference field?

I have a table that showed the type of coaching and a reference field that shows the individuals who practice the coaching types. I am trying to show a table that shows the coaching types and the number of people against each coaching type.

Here is the code I have. I am not sure where is going wrong so the the new property is not generated (totalCoaches was never added to the item). When I use console log to check the results, they were logged though the results were far more than the number of IDs which is really weird. If anyone knows how to fix this or a better way to do this, please shed some light. Thanks!

import wixData from ‘wix-data’;

export function CoachingAreas_afterQuery(item, context) {
item.totalCoaches = findNumCoaches(item._id);
return item;
}

const findNumCoaches = (id) => {
wixData.queryReferenced(“CoachingAreas”,id,“coachName”)
.then( (results) => {
return results.totalCount;
} )
. catch ( (error) => {
console.log(“incorrect”);
} );
};

Hey
First of all, why do you use a data hook? Move your function into the page code to test it first anyway. You are using afterQuery and then you query the same data collection in the function which will loop this until a timeout occurs I guess.

so, tip from me. Run the code first in page code and when it works create a backend function for it. Use only data hooks when you want to modify or notify something or someone when data is used.

@ Andreas Kviby

Are there any notable draw backs from using backend functions ?

@mikemoynihan99 No, everything goes faster

Hey thanks for the reply. I’ve resolved the loop problem by moving findNumCoaches into a different backend file. However a new problem occurred: the after query data hook does not wait for findNumCoaches to finish, so the calculated data is not available when querying. What would be a better way to resolve this? Thanks!