How i can pass an object to an attribute of an object?

Viewed 88

I have this code in reducer:

export const getSerieSuccess = (state = INITIAL_STATE, action) => {
   return {
      ...state,
      isLoadding: false,
      serie: action.serie   //action.serie is a object with id, name, genre e status
   }
}

I want to know if i do serie: action.serie, i am passing a value or a reference. I did this like:

export const getSerieSuccess = (state = INITIAL_STATE, action) => {
const serie = {...action.serie};
   return {
      ...state,
      isLoadding: false,
      serie
   }
}

How wai is better working with functional programming?

1 Answers

You can use both variants as long as the payload of the action is not further referenced and will not be mutated/changed.

Good:

store.dispatch(new SomeAction({a: b: {
  c: 1234
}));

Bad (because you pass a reference and change it afterwards):

let value = new SomeAction({a: b: {
  c: 1234
});
store.dispatch(value);
value.a.b.c = 44543; // bad

setTimeout(_ => (value.a.b.c = 5555), 5000); // bad

Note: if you want to make it really save (no reference passing) you could make a copy of the passed value inside of the action.

Related