Problem
I have two inputs that triggers an event, which will update an quantity of a certain product (Those inputs are referenced to a product).
And since I can write an number, for example, the quantity, very fast, it is usually slow.
Takes 1-2 seconds (When I have more products) to update the quantity of the product...
The function that updates the product will return a new basket which is basically the "cart", where all products are, and then I'll update the old one with the new one (with the modifications).
What kind of performance improvement should I implement?
Note: I'm using React and the function belongs to a Context API.
Method: modifyProductQuantity()
export const modifyProductQuantity = (
productToModify: ProductInterface,
quantity: number,
basket: ProductInterface[]
): ProductInterface[] => {
const basketWithUpdatedProduct = basket.map((product) => {
if (product.id === productToModify.id) {
const totalPrice = product.pricePerMeasurement * quantity;
const roundedTotalPrice = parseFloat(totalPrice.toFixed(2));
const roundedTotalQuantity = parseFloat(quantity.toFixed(2));
return {
...product,
quantity: roundedTotalQuantity,
price: roundedTotalPrice,
};
}
return product;
});
return basketWithUpdatedProduct;
};
My Possible Solution:
I might be able to achieve a better performance if I handle the product modification in the background, and it works like this:
- Every time I change the input I run a setTimeOut of 3 seconds, for example.
- If I change the input again, another setTimeOut will be run.
- Therefore I would only run the function when the user stops typing
What do you guys think???