i am updating state in form by dynamically adding form fields but this error is ing up what i have tried what should happen is that more fields should be added to each subfields on click if i want
const addExperience = () => {
let temp = Object.assign({}, form);
temp.experience.push({
pany: "",
position: "",
startDate: "",
endDate: "",
description: "",
});
setForm(temp);
}
this is the form
const [form, setForm] = useState({
name: "adarsh raj",
email: "[email protected]",
phone: "83404dvsdsd",
address: "patel chowk",
city: "deoghar",
education: [
{
school: "dav ",
major: "intermediate",
GPA: "8.12",
},
],
experience: [
{
pany: "venturepact llc",
position: "associate software developer",
startDate: "dd-mm-yyyy",
endDate: "dd-mm-yyyy",
description: "description",
},
],
projects: [
{
projectName: "project name",
projectDescription: "project description",
},
],
skills: [
{
skillName: "your skill name",
},
],
});
i am updating state in form by dynamically adding form fields but this error is ing up what i have tried what should happen is that more fields should be added to each subfields on click if i want
const addExperience = () => {
let temp = Object.assign({}, form);
temp.experience.push({
pany: "",
position: "",
startDate: "",
endDate: "",
description: "",
});
setForm(temp);
}
this is the form
const [form, setForm] = useState({
name: "adarsh raj",
email: "[email protected]",
phone: "83404dvsdsd",
address: "patel chowk",
city: "deoghar",
education: [
{
school: "dav ",
major: "intermediate",
GPA: "8.12",
},
],
experience: [
{
pany: "venturepact llc",
position: "associate software developer",
startDate: "dd-mm-yyyy",
endDate: "dd-mm-yyyy",
description: "description",
},
],
projects: [
{
projectName: "project name",
projectDescription: "project description",
},
],
skills: [
{
skillName: "your skill name",
},
],
});
Share
Improve this question
asked Oct 28, 2021 at 7:26
Adarsh RajAdarsh Raj
3235 silver badges17 bronze badges
3 Answers
Reset to default 5I solved now a similar problem creating a new array with spread operator like this
const newMutableArray = [...immutableArray, newItem]
it works fine for me.
Object.assign(target, source)
just Shallow copy.
useState
return value is Immutable;
Refer to the following demo
var x = new Array(10).fill(0);
Object.freeze(x);
x.push(11) // same error
You can solve this problem by deep copying
or reassigning the experience of the first layer
.
Only the first layer can be assigned because a shallow copy is used. It cannot be resolved if the problem attribute appears at the second level. Therefore, this method is not remended and deep copy is remended.
let temp = JSON.parse(JSON.stringify(form));
let temp = lodash.cloneDeep(form);// need install lodash
code like this should work. But to test, you can try this syntax:
const addExperience = () => {
let temp = Object.assign({}, form);
temp.experience = [
...temp.experience,
{
pany: "",
position: "",
startDate: "",
endDate: "",
description: ""
}
];
setForm(temp);
};