skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    newValues = user['contacts'].map(section => {
        return ({ ...section, ['name']: e.target.value })
    })
    
    setUser(prev => ({
        ...prev, contacts:
            newValues
    }));
    

  2. In the contacts part of the new object, you need to spread only the original contacts part and not the whole prev state.

    const handleChange = (e) => {
      setUser(prev => ({
        ...prev,
        contacts: [{
          ...prev.contacts, // you need the .contacts here
          name: e.target.value
        }]
      }))
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search