I have a state that contains an array of objects. I added order so I can group the object based on the order. A new bunch of objects will be created when a button is clicked and the new objects order value will increase
const initialData = [
{
name: "point",
label: "Point",
order: 1
},
{
name: "optionA",
label: "A",
order: 1
},
{
name: "optionB",
label: "B",
order: 1
},
];
Here is what I tried. I used reduce to group the data based on order when a button is clicked. The order value changes but the array the new array is not populating
const [formData, setFormData] = useState(initialData)
const addMoreField = () => {
const groups = formData.reduce(
(groups, item) => ({
...groups,
[item.order]: [
...(groups[item.order] || []),
{ ...item, order: item.order++ }
]
}),
{}
);
setFormData(groups)
console.log("groups", groups);
console.log("formData", formData);
}
The addMoreField function is supposed to increment the order and create a new array with more groups.
const newData = [
1: [
{
name: "point",
label: "Point",
order: 1
},
{
name: "optionA",
label: "A",
order: 1
},
{
name: "optionB",
label: "B",
order: 1
},
],
2: [
{
name: "point",
label: "Point",
order: 2
},
{
name: "optionA",
label: "A",
order: 2
},
{
name: "optionB",
label: "B",
order: 2
},
]
]
implementation on codesandbox
item.order+1,item.order++incrementsorderin the original state (which is not good), but returns the value ofitem.orderbefore any increment occurs