0

I having to issues with my code. the first one is that I am trying to format The Total as currency but it does not work. my second issues is I am using the Reduce() method to track and calculate the price when ever the user selects the item till here it works find, but when the user unselects an item it goes back to zero . I do not that I just want to mince it and keep the selected once .

const items = useSelector((state) => state.cartReducers.selectedItems.items);
 
const Total = items
  .map((item) => Number(item.price.replace("$", "")))
  .reduce((prev, curr) => prev + curr, 0);
    
const USD = Total.toLocaleString("en", {
  style: "currency",
  currency: "USD",
});
7
  • Clarify the first issue, what exactly doesn't work. What you expect and what you get? Regarding the second issue, use a ref to store previous selected items and read from it so even if the state changes the value will remain there. Commented Mar 30, 2022 at 21:51
  • 1
    toLocaleString expects a number as input - ie. let num = 1000; num.toLocaleString("en-US", {style:"currency", currency:"USD"}) this will give you an output of '$1,000.00' - this also means that your replace function is unnecessary, as the toLocaleString will add the '$' Commented Mar 30, 2022 at 21:55
  • For the second issue, I'm not exactly sure what you're trying to achieve - mapping and reducing will not change the original array, so items will go back to its original value on each render Commented Mar 30, 2022 at 21:58
  • okay the price var in the array is like this 12.50$ so it string . fisrt I have to replace the $ with empty string so it become like this "12.50" the format it as a number so I can calculate. till here it works fine. but when I unselect an item it becomes 0 again Commented Mar 30, 2022 at 22:01
  • First issue I expect the output to be like this $12.50 but it prints 12.50 Commented Mar 30, 2022 at 22:04

1 Answer 1

2

Try to change en to en-US

 const USD = Total.toLocaleString('en-US',
  {style: 'currency', currency: 'USD'}
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.