0

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)}
1
  • Have you considered using separate state variables instead? Commented Nov 4, 2022 at 0:11

1 Answer 1

1

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

In recommendation territory, there's react-hook-form.com.
@OFRBG I prefer formik.org

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.