I have been working with React Hooks for a while, but the biggest problem for me is working with arrays.
How to update value of nested array of objects? I want to change dropdown type. My code is below and changes the state directly. How can I fix this? What is the most correct code?
Thanks for your help.
const [grups, setGrups] = useState([
{
id: 1,
css: "col",
components: [
{ id: 1, type: "textbox" },
{ id: 2, type: "integer" },
],
},
{
id: 2,
css: "col",
components: [
{ id: 1, type: "numerictextbox" },
**{ id: 2, type: "dropdown" },**
],
},
]);
function handleClick(gindex,cindex) {
const newgrups = [...grups];
newgrups[gindex] = {...grups[gindex] ,components: [...grups[gindex].components]};
newgrups[gindex].components[cindex].tip="datetime";
setGrups(newgrups);
}
newgrups[gindex].components[cindex].tip="datetime";-> to ->newgrups[gindex].components[cindex] = {...newgrups[gindex].components[cindex], tip: "datetime"};to avoid mutating that last nested object.useReduceror Redux, or Mobx. Whatever works best for you. Right now every time one item in the array is updated the entire state is updates, and you just need to update one item. IMO, I think 99% of the timeuseReducerwill cover you.