How To Update With React Hooks Specific Value Of An Array Inside An Object?
I have an object which i want to update it using React Hooks const [rowEdit, setRowEdit] = useState({ rowEdit: { '1x0': [1, 1, 1, 1, 1] } }); I loop through the array with .map, s
Solution 1:
You can return 0
if the map
index is equal to 1
, or return the current element otherwise.
Example
const { useState } = React;
functionApp() {
const [rowEdit, setRowEdit] = useState({
rowEdit: { "1x0": [1, 1, 1, 1, 1] }
});
functiononClick() {
setRowEdit(prevState => ({
...prevState,
rowEdit: {
...prevState.rowEdit,
"1x0": prevState.rowEdit["1x0"].map((row, index) =>
index === 1 ? 0 : row
)
}
}));
}
return (
<div><buttononClick={onClick}>update row</button><div>{JSON.stringify(rowEdit)}</div></div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<scriptsrc="https://unpkg.com/react@16/umd/react.development.js"></script><scriptsrc="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><divid="root"></div>
Solution 2:
It's unclear if you want to do this for all keys in the object, but I'm going to assume you do:
setRowEdit(rows =>Object.entries(rows).reduce((obj, [rowId, row]) => ({
...obj,
[rowId]: row.map((col, i) => i === 1 ? 0 : col),
}), {}));
Otherwise:
setRowEdit(rows => ({
...rows,
'1x0': rows['1x0'].map((col, i) => i === 1 ? 0 : col),
}), {}));
Post a Comment for "How To Update With React Hooks Specific Value Of An Array Inside An Object?"