I am trying to make an API request based on the result of another API request.
(我正在尝试根据另一个API请求的结果发出一个API请求。)
I got it working the way I want it but I don't like to use forEach for my API call and I can't wrap my head around how to get in done with a different method.(我以自己想要的方式运行它,但是我不喜欢在API调用中使用forEach,而且我无法解决如何使用其他方法来解决问题。)
Are there any suggestions on how I could do it in a more efficient way, eg.(是否有关于如何以更有效的方式进行操作的建议,例如)
with promise.all?(与promise.all?)
here is my code:
(这是我的代码:)
api.js
(api.js)
export const fetchOrders = () => {
return fetch(`${url}/work_orders`).then(res => res.json());
};
export const fetchWorker = id => {
return fetch(`${url}/workers/${id}`).then(res => res.json());
};
app.js
(app.js)
function OrderReducer(state, action) {
if (action.type === "fetch") {
return {
orders: [],
error: null,
loading: true
};
} else if (action.type === "success") {
return {
...state,
orders: [
...state.orders,
{
order: action.order,
worker: action.worker
}
],
loading: false
};
} else if (action.type === "error") {
return {
...state,
error: action.message,
loading: false
};
} else {
throw new Error("no action type initialized");
}
}
const Orders = () => {
const [state, dispatch] = React.useReducer(OrderReducer, {
orders: [],
error: null,
loading: true
});
React.useEffect(() => {
dispatch({ type: "fetch" });
fetchOrders()
.then(({ orders }) => {
return orders;
})
.then(orders =>
orders.forEach(order => {
fetchWorker(order.workerId).then(({ worker }) =>
dispatch({ type: "success", order, worker })
);
})
)
.catch(({ message }) => dispatch({ type: "error", message }));
}, []);
archived output:
(存档的输出:)
orders:[
0: {
order:{...},
worker:{...}
},
...
...
...
20: {
order:{...},
worker:{...}
}
]
ask by Maurice Oppenberger translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…