Home > Blockchain >  Updating multiple attributes of a nested state array of objects from a dynamic object
Updating multiple attributes of a nested state array of objects from a dynamic object

Time:12-31

I am trying to update a nested state array with an object with dynamic keys but have something slightly off and was hoping someone may be able to help guide me in the right direction:

state array: 
[
   0: { createdTime: 'XXX',
        id: 'XXX',
        fields: {
           k1: v1,
           k2: v2,
           k3: v3,
      }
]

I have a functional component returning an object like:

e = { k2: v4 }

the follow code is close but a little off:

onInfoEditSubmit = (props, e, n) => {
    if (Object.keys(e).length > 0) {
        let dl = new DataLayer()
        dl.updateStartupRecord(props.current_startup_or_engagement.id, e)
        this.setState(prevState => ({

            startup_records: prevState.startup_records.map(
                r => r.id === props.current_startup_or_engagement.id ?
                    { ...r,
                        fields: {
                            ...r.fields,
                            e
                        }
                    }: r
            )

        }))
    }
}

new state array after this code:

state array: 
[
   0: { createdTime: 'XXX',
        id: 'XXX',
        fields: {
           k1: v1,
           k2: v2,
           k3: v3,
           e: {k2: v4}
      }
]

I was following this post: Updating an object with setState in React

In this example I am only updating a single property but would like this to work for multiple new values, so an input object might look like:

e = {k2: v4, k3: v5}

Can I do what I am trying to do with this method? Any help would be greatly appreciated, thanks!

CodePudding user response:

You need to use the spread operator for e as well:

onInfoEditSubmit = (props, e, n) => {
    if (Object.keys(e).length > 0) {
        let dl = new DataLayer()
        dl.updateStartupRecord(props.current_startup_or_engagement.id, e)
        this.setState(prevState => ({

            startup_records: prevState.startup_records.map(
                r => r.id === props.current_startup_or_engagement.id ?
                    { ...r,
                        fields: {
                            ...r.fields,
                            ...e // spread operator here
                        }
                    }: r
            )

        }))
    }
}
  • Related