0

I need to push a new object into the state variable without getting the previous values removed. My state is

this.state = {
files:{
    file1: 
    {
        user1:[{
                key1: val1,
                key2: val2,
                key3: val3
            },
            {
                key1: val1,
                key2: val2,
                key3: val3
            }
        ]
    }
}   
}

I need to update the files as

files:{
    file1: 
    {
        user1:[{
                key1: val1,
                key2: val2,
                key3: val3
            },
            {
                key1: val1,
                key2: val2,
                key3: val3
            }
        ]
    },
    file2: 
    {
        user2:[{
                key1: val1,
                key2: val2,
                key3: val3
            },
            {
                key1: val1,
                key2: val2,
                key3: val3
            }
        ]
    }
}

I need to push a new object file2 into the state having values in the same structure as file1. How can I update the state with these two objects?

Hinrich
  • 13,485
  • 7
  • 43
  • 66
Hareesh S
  • 197
  • 1
  • 2
  • 12
  • The recommended way to achieve this is by using array destructuring. https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Op%C3%A9rateurs/Affecter_par_d%C3%A9composition – Swann Jun 06 '18 at 09:27

2 Answers2

1

You should use the setState function expression, so you can access the previous state:

addFile(newFile) {
  this.setState(state => ({
    files: {...state.files, ...newFile}
  })
}

newFile should be an object that looks like this:

{
  file2: {
    ...
  }
}

This object gets merged into the previous state. If there already was an entry with the same key (file2), it would get overridden.

Hinrich
  • 13,485
  • 7
  • 43
  • 66
  • This gives the result as array. `file1` inside 0th key and `file2` inside 1st key. I need the keys shouls be `file1` and `file2` and not as `0` or `1` – Hareesh S Jun 06 '18 at 10:27
  • I see. Updated my answer. – Hinrich Jun 06 '18 at 10:29
  • This is working @Hinrich. The objects are sorted based on the alphabetical order or keys. Eg: `File1` , `File2` etc. How can I arrange them based on the pushing order? – Hareesh S Jun 06 '18 at 11:13
  • Objects are unsorted by nature, think of it as Sets. If order is important to you, you should store your data in an `array`. – Hinrich Jun 06 '18 at 11:28
0

You can achieve this by using spread operator. It can be added as follows:

this.setState({
    file1: [...this.state.file1,{key1:'val1',key2:'val2',key3:'val3'}]
})
Mahipal
  • 344
  • 2
  • 13