Hareesh S
Hareesh S

Reputation: 207

How to push a new object into state without removing the previous values in React

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?

Upvotes: 0

Views: 1089

Answers (2)

Hinrich
Hinrich

Reputation: 13983

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.

Upvotes: 1

Mahipal
Mahipal

Reputation: 519

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'}]
})

Upvotes: 0

Related Questions