I am trying to update the total count of each type of orders that are available before rendering it to UI. I am facing issue with the count not updating correctly for the particular key.
I have 3 small snippets of the code.
Dummy JSON
export let orders = [
{
id: "1000",
dateTime: "Tue 13 Jun 11:52 AM",
merchant: "RAJUGARI VINDU BOJANAM",
customer: "Purnima Reddy",
items: "3",
total: "862.42",
type: "Delivery",
payment: "cod",
status: "Completed",
notes: "Good",
},
{
id: "1001",
dateTime: "Tue 13 Jun 11:52 AM",
merchant: "RAJUGARI VINDU BOJANAM",
customer: "Purnima Reddy",
items: "3",
total: "862.42",
type: "Delivery",
payment: "cod",
status: "Completed",
notes: "",
},
{
id: "1002",
dateTime: "Tue 13 Jun 11:52 AM",
merchant: "RAJUGARI VINDU BOJANAM",
customer: "Purnima Reddy",
items: "3",
total: "862.42",
type: "Delivery",
payment: "cod",
status: "Pending",
notes: "Something is better",
},
{
id: "1003",
dateTime: "Tue 13 Jun 11:52 AM",
merchant: "RAJUGARI VINDU BOJANAM",
customer: "Purnima Reddy",
items: "3",
total: "862.42",
type: "Delivery",
payment: "cod",
status: "Cancelled",
notes: "",
},
{
id: "1004",
dateTime: "Tue 13 Jun 11:52 AM",
merchant: "RAJUGARI VINDU BOJANAM",
customer: "Purnima Reddy",
items: "3",
total: "862.42",
type: "Delivery",
payment: "cod",
status: "Collected",
notes: "",
},
{
id: "1005",
dateTime: "Tue 13 Jun 11:52 AM",
merchant: "RAJUGARI VINDU BOJANAM",
customer: "Purnima Reddy",
items: "3",
total: "862.42",
type: "Delivery",
payment: "cod",
status: "Ready",
notes: "",
},
{
id: "1006",
dateTime: "Tue 13 Jun 11:52 AM",
merchant: "RAJUGARI VINDU BOJANAM",
customer: "Purnima Reddy",
items: "3",
total: "862.42",
type: "Delivery",
payment: "cod",
status: "Accepted",
notes: "almost",
},
{
id: "1007",
dateTime: "Tue 13 Jun 11:52 AM",
merchant: "RAJUGARI VINDU BOJANAM",
customer: "Purnima Reddy",
items: "3",
total: "862.42",
type: "Delivery",
payment: "cod",
status: "Completed",
notes: "almost",
},
];
In Rendering JS File
useState Part
let [counts, setCounts] = useState({
All: orders.length,
Pending: 0,
Accepted: 0,
Ready: 0,
Collected: 0,
Completed: 0,
Cancelled: 0,
});
useEffect Part
useEffect(() => {
for (let i = 0; i < orders.length; i++) {
let key = orders[i].status;
let prevValue = counts[orders[0].status];
setCounts((counts) => ({ ...counts, [key]: prevValue + 1 }));
}
}, []);
In useEffect I am trying to loop through the elements and store keys of counts in key variable. Storing previous value in prevValue. While setting the value I am spreading it as well. Not sure why the output in the console is all 1 even if the count of some key is more like “Completed”
