DEV Community

Randy Rivera
Randy Rivera

Posted on • Updated on

Redux: Copy an Object with Object.assign

  • The last posts worked with arrays, but there are ways to help enforce state immutability when state is an object. A useful tool for handling objects is the Object.assign()
  • Object.assign() takes a target object and source objects and maps properties from the source objects to the target object. This is used to make shallow copies of objects by passing an empty object as the first argument followed by the object(s) you want to copy.

  • Example:

const myObject = Object.assign({}, obj1, obj2);
Enter fullscreen mode Exit fullscreen mode
  • This creates myObject as a new object, which contains the properties that currently exist in obj1 and obj2.

  • Code:

const defaultState = {
  user: 'CamperBot',
  status: 'offline',
  friends: '732,982',
  community: 'freeCodeCamp'
};

const immutableReducer = (state = defaultState, action) => {
  switch(action.type) {
    case 'ONLINE':
      // Don't mutate state here or the tests will fail
      return
    default:
      return state;
  }
};

const wakeUp = () => {
  return {
    type: 'ONLINE'
  }
};

const store = Redux.createStore(immutableReducer);
Enter fullscreen mode Exit fullscreen mode
  • Here we have a Redux state and actions that were modified to handle our object situation. We need to edit the code to return a new state object for actions with the type ONLINE, which set the status property to the string online

*Answer:

const defaultState = {
  user: 'CamperBot',
  status: 'offline',
  friends: '732,982',
  community: 'freeCodeCamp'
};

const immutableReducer = (state = defaultState, action) => {
  switch(action.type) {
    case 'ONLINE':
      const myObject = Object.assign({}, state, {status: 'online'})
      return myObject;
    default:
      return state;
  }
};

const wakeUp = () => {
  return {
    type: 'ONLINE'
  }
};

const store = Redux.createStore(immutableReducer);
Enter fullscreen mode Exit fullscreen mode

Larson, Q., 2019. Frontend Development Libraries. [online] Freecodecamp.org. Available at: https://www.freecodecamp.org/learn/front-end-development-libraries/redux

Discussion (0)