I’m working on an application that involves a somewhat complex user registration. Something similar to this.
const [data, setData] = useState({ identity: '', people: [{ name: '', address: [{ street: '', city: '' }] }] }) function addAddress(){ setData({ ...data, people: [ ...data.people, { address: [ ...data.people[0].address, { street: '', city: '' } ] } ] }) }
When a user adds a new address to a person he is registering, he should add a new address to the person and keep the previous data. But it creates a new data array with just the address data, outside of the specified person.
Could someone help me how to do this insertion into the array?
Advertisement
Answer
It’s not the best solution i guess, but it should work
I’m using here JSON.stringify()
and JSON.parse()
to deep copy your previous data
function addAddress (newAddress) => { setData((previousData) => { let newData = JSON.stringify(previousData); newData=JSON.parse(newData); newData.people[0].address.push(newAddress); return (newData); }); }