I have This structure data That I received in JSON: (I’m can’t modify it for it’s not me that works on the API) and I have to update the JSON file with the modification made by the user.
{
"id": 1269,
"name": "Fet",
"firstname": "Boba",
"contacts": [
{
"id": 2,
"name": "Ema Tal",
}
]
}
I get the JSON and put it in a localStorage, then I update the localStorage et return te JSON to the api for UPDATE.
const [user, setUser] = useState();
const handleChange = (e) => {
setUser(prev => ({
...prev, contacts: [
{ ...prev, name: e.target.value }
]
}))
}
I can’t seem to figure out the way it output it in the same order and only replacing data without adding a new contact on each typo.
the problem I have is that every time I update the file, it replace the NAME that is not in Contacts or it create new contacts in contatcs
example of replace the name NOT in contacts
{
"id": 1269,
"name": "Ema tal", <-- same not good
"firstname": "Boba",
"contacts": [
{
"id": 2,
"name": "Ema Tal", <-- same not good
}
]
}
and an example of what I meen by creating new contacts in contacts (that is not good either)
{
"id": 1269,
"name": "Fet",
"firstname": "Boba",
"contacts": [
{
"id": 2,
"name": "Ema Tal",
},
"contacts": [
{
"id": 2,
"name": "Ema Tal 2",
}
]
]
}
I need the data to update exacly like this (the same way it come in.)
{
"id": 1269,
"name": "Fet",
"firstname": "Boba",
"contacts": [
{
"id": 2,
"name": "Ema Tal updated",
}
]
}
2
Answers
If this can help someone else, I found what works for me, and your input helps me find the solution.
Since I have an object that contains an array of other objects I needed a map in there like this.
In the
contacts
part of the new object, you need to spread only the originalcontacts
part and not the wholeprev
state.