UnskilledCoder
UnskilledCoder

Reputation: 312

How does reducer can work with an object with duplicate keys?

Learning React with Redux, the course author wrote this:

export default (state = [], action) => {
  switch (action.type) {
    case FETCH_STREAM:
      return { ...stream, [action.payload.id]: action.payload };
    case CREATE_STREAM:
      return { ...stream, [action.payload.id]: action.payload };
    case EDIT_STREAM:
      return { ...stream, [action.payload.id]: action.payload };
    default:
      return state;
  }
};

As much as I understood, the { ...stream, [action.payload.id]: action.payload } pattern is a new JavaScript syntax called "Key Interpolation Syntax" and what it does is that it adds a new key/value to our object ( which we have made a copy of it with spread ... syntax first ) so in that case I do understand the CREATE_STREAM one, but how about EDIT_STREAM ? Is it gonna replace the key because the key is already in there? or is it gonna blindly add it so then duplicate key? Also I don't understand the FETCH_STREAM at all. Why is it even like this? Shouldn't it just be a return action.payload ?

Upvotes: 0

Views: 178

Answers (1)

Alyson Maia
Alyson Maia

Reputation: 810

Actually, the Key Interpolation syntax will add that key if it doesn't exist but will override its value if it is duplicated.

The following code

const personA = {
  name: 'John Doe',
  age: 42
};

const createdProp = 'country';
const overriddenProp = 'age';

const personB = {
  ...personA,
  [createdProp]: 'USA',
  [overriddenProp]: 50
};

Will result in personB with these values

{
  name: "John Doe",
  age: 50,
  country: "USA"
}

About the FETCH it depends on what they intended. If the spread operation is removed, then all previous data will be lost. If that is no problem, you can do { [action.payload.id]: action.payload } without worries.

Upvotes: 1

Related Questions