I have this array object to begin with
[
{
"name": "child",
"pax": {}
}
]
I wish to append new property which is an array. then I want to update/insert new object into that array. But something is wrong with my code
function App() {
const [num, setNum] = useState(0);
const [arr, setArr] = useState([
{
name: "child",
pax: {}
}
]);
function appendage({ id, age }) {
const toSaveArr = arr.map(o => {
if (o.name === "child") {
return {
...o,
age: o.age
? o.age.map(o2 => {
if (o2.id === id) {
return {
id: o2.id,
age
};
}
console.log("o2", o2);
//something is wrong here
//why is it not adding new object?
return [
...o2,
{
id,
age
}
];
})
: [{ id, age }]
};
}
return o;
});
setArr(toSaveArr);
}
return (
<div className="App">
<h1>{num}</h1>
<button
onClick={() => {
setNum(num + 1);
appendage({
id: num + 1,
age: num + 1
});
}}
>
add
</button>
<button>update age where id equal to 2</button>
<pre>{JSON.stringify(arr, null, 2)}</pre>
</div>
);
}
https://codesandbox.io/s/pedantic-mclean-107q2
I think I've used spread operator wrongly here.