I am trying to get a combined result from multiple promises inside a React hook.
But when I use the hook, the function getAll immediately returns empty, instead of returning all MyTypes.
My Hook: (api.get returns a Promise<MyType[]>)
function useMyHook() {
const api = useApiService();
return {
getAll,
};
function getAll(arr: number[]): MyType[] {
const results: MyType[] = [];
for (const u of arr) {
api.get(u).then((res) => {
results.push(...res);
});
}
return [...new Set(results)];
}
}
Usage:
function MyComponent() {
// ...
const myHook= useMyHook();
const use = () => {
// ...
const numbers = [1, 2, 3];
const myTypes = myHook.getAll(numbers);
const count = myTypes.length; // this will always be 0
// ...
};
}
How can I make this work? I have tried multiple versions with promise chaining and async/await, but to no avail.