React – update state array

Context

Hi,

I’m creating a form to create virtual machine. Informations are gathered across multiple pages (components) and centralized in top level component.

It’s state object looks like this :

const [vmProp, setVmProp] = useState({
    name: "",
    image_id: "",
    image_name: "",
    volumesList: [],
    RAM: "",
    vcpu: "",
    autostart: true,
    });

Problem

I want to be able to add/remove a volume to the volumes List and I want volumesList to looks like this :

[
    {
      name: "main",
      size: 1024
    },
    {
      name: "backup",
      size: 2048
    },
    {
      name: "export",
      size: 2048
    }
]

What I’ve tried

For now I’ve only tried to add a volume.

1 : working but does not produce what I want

const handleAddVolume = (obj) => {
    setVmProp({ ...vmProp,
        volumesList: {
            ...vmProp.volumesList,
            [obj.name]: {
                size: obj.size,
            },
        } });
};

It’s working but the output is :

[
    name: {
      size: 1024
    }
]

2 : should be working but it’s not

const handleAddVolume = (obj) => {
    setVmProp({ ...vmProp,
        volumesList: {
            ...vmProp.volumesList,
            {
                name: obj.name,
                size: obj.size,
            },
        } });
};

output :

[
    name: "main",
    size: 1024

]

Do you have any ideas on how to handle such state object ? Thanks

Answer

You’ll have a better time if you don’t need to nest/unnest the volumes list from the other state. (Even more idiomatic would be to have a state atom for each of these values, but for simple values such as booleans and strings, this will do.)

const [vmProps, setVmProps] = useState({
  name: "",
  image_id: "",
  image_name: "",
  RAM: "",
  vcpu: "",
  autostart: true,
});
const [volumesList, setVolumesList] = useState([]);