I am trying to update the state using the useState hook for React. However, I think I am using it incorrectly or at least not how it's intended.
I have a class which is initialised.
const [form, setForm] = useState(new Form());
I am then adding elements to this form:
const element = ...
setForm(form => ({
...form,
elements: [
...form.elements,
element
]
});
However, this doesn't seem to update the UI to reflect this change.
I have also tried the following:
setForm(form => {
form.elements.push(element);
return form;
});
The only way I can get it to work is doing the following and as you can imagine it becomes quite a mountain to climb as it's a bit all over the place:
const duplicated = JSON.parse(JSON.stringify(form));
duplicated.elements.push(element);
setForm(new Form(duplicated));
Is there a better approach to do this rather than having to duplicate the object everytime.