I am making an online store and I want to calculate the total cost of products in it. The cart looks like this: [{productId, count}, {productId, count}], and I get the cost of the product through a query by productId.
Below is an example of what the ideal structure looks like that I would like to get, but useQuery cannot be used inside a map and useQuery is asynchronous. I've already tried various ways to solve this, but to no avail.
Can you please tell me how to solve this problem or is there another way?
import {useQuery, useMutation} from "@apollo/client";
import {GET_PRODUCT_PRICE} from "../query/product";
export const GetTotalPrice = (cart) => {
let totalPrice = 0;
const {data, loading, error} = useQuery(GET_PRODUCT_PRICE, {
variables: {
id: productId
}
});
cart.map((product) => {
const {data, loading, error} = useQuery(GET_PRODUCT_PRICE, {
variables: {
id: product.productId
}
});
totalPrice += data.getProduct.price * product.count;
})
return totalPrice;
}