If you're new to ES6 and you have seen the code below your most likely wondering what dark sorcery is held within those three dots. This is the new object spread operator and it's very powerful.
{...state, places: action.places};
From a high level what is happening is that all the values of our "state" variable are being added to a new object, a new key called "places" is also created within the same object. Try some of the examples below and try to work them out in your head before looking at the answer.
let user = {username: 'user1', password: 'password'};
let newUser = {...user, phone: '086 4234544'};
console.log(newUser);
{ username: 'user1', password: 'password', phone: '086 4234544' }
// Simple right?
let user = {username: 'user1', password: 'password'};
let newUser = {...user, username: 'jimmy'};
console.log(newUser);
{ username: 'jimmy', password: 'password' }
// If you figured out that the right-most key-value takes precedence then good job
let user = {username: 'user1', password: 'password'};
let info = {number: '087 63455424', address:'Cork, Ireland'};
let result = {...user, ...info};
console.log(result);
{ username: 'user1', password: 'password', number: '087 63455424', address: 'Cork, Ireland' }
// You can easily spread multiple objects
let user = {username: 'user1', address: {line1: 'Cork', line2: 'Ireland'}};
let newUser = {...user, address: {line2: 'Jamaica'}};
console.log(newUser);
{ username: 'user1', address: { line2: 'Jamaica' } }
// If your wondering where line1 went from the address don't worry, this is a common gotcha.
// If we wanted to keep line1 of our address then we need to spread this also using the example below
let user = {username: 'user1', address: {line1: 'Cork', line2: 'Ireland'}};
let newUser = {...user, address: {...user.address, line2: 'Jamaica'}};
console.log(newUser);
{ username: 'user1', address: { line1: 'Cork', line2: 'Jamaica' } }}
let users = {
user1: {
username: 'timmy'
},
user2: {
username: 'jimmy'
},
user3: {
username: 'tommy'
}
};
let result = {...users, ['user2']: {...users.user2, password: 'jimmypass'}};
console.log(result);
{ user1: { username: 'timmy' }, user2: { username: 'jimmy', password: 'jimmypass' }, user3: { username: 'tommy' } }
// We simply gave jimmy a password. This is a good example of how you update a user based on their user key
let users = ['user1', 'user2'];
let newUsers = ['user3', 'user4'];
let allUsers = [...users, ...newUsers];
console.log(allUsers);
['user1', 'user2', 'user3', 'user4']
// This demonstrates that we can also spread arrays
If you didn't get all the questions correct then do not worry, this new syntax takes some getting used to, however, when get used to it you will see how powerful it can be.