h_bjergen
h_bjergen

Reputation: 63

How to update UseState nested array with spread in React?

I have three checkboxes and I would like to push the value to the equipment array in the below hook e.g.: if 2 boxes ticked the array should look like:

equipment: [{id: '1', name: 'bag', amount: 1}, {id: '2', name: 'phone', amount: 4}]
    const [form, setForm] = useState({
        firstName: "",
        lastName: "",
        middleName: "",
        position: "",
        level: "",
        equipment: []
    });

Is it a proper way to update the array or how should I do it with spread?

setForm({...form, ...form.equipment.push(value)}

Upvotes: 0

Views: 99

Answers (1)

Phil
Phil

Reputation: 164745

In order to update state based on the current value, you should use the functional updates form for calling the setter. For example

setForm((prev) => ({
  ...prev,
  equipment: prev.equipment.concat(value),
}));

Putting all your state into a single object makes your code more complicated. Have you considered simply using separate variables?

const [firstName, setFirstname] = useState("");
const [lastName, setLastName] = useState("");
// ...
const [equipment, setEquipment] = useState([]);

// and when setting equipment...
setEquipment((eq) => [...eq, value]);

If you do need everything in a single object, you can always use a memo hook

const form = useMemo(() => ({
  firstName,
  lastName,
  middleName,
  position,
  level,
  equipment,
}), [firstName, lastName, middleName, position, level, equipment]);

Upvotes: 1

Related Questions