3

I have a state Object that looks like this:

//State Object
playlistDict: {
  someId1: {
    active: false,
    id: 'someId',
    name: 'someName',
    pages: [ 'pageId1', 'pageId2', 'pageId3', etc ]  // I want to remove an element from this array
  },
  someId2: {
    active: false,
    id: 'someId2',
    name: 'someName2',
    pages: [ 'pageId11', 'pageId22', 'pageId33', etc ] // I want to remove an element from this array
  }
}

I'm trying to write a reducer that removes a page element given the index to remove without using immutability helper.

This is what I'm trying to do but my syntax is off and I'm not sure what's the correct way to write the reducer:

export function _removePageFromPlaylist( playlistId, pageIndex ) {
  return { type: types.REMOVE_PAGE_FROM_PLAYLIST, playlistId, pageIndex };
}

case types.REMOVE_PAGE_FROM_PLAYLIST: {    
      let playlistCopy = Object.assign( {}, state.playlistDict[ action.playlistId ]);
      playlistCopy.pages = Object.assign( {}, state.playlistDict[ action.playlistId ].pages );
      playlistCopy.pages.splice( action.pageIndex, 1 );

      return Object.assign({}, state, {
        playlistDict: { ...state.playlistDict, playlistDict[ action.playlistId ]: playlistCopy }  // doesn't like this syntax in particular
      });
    }

EDIT: In regards to people thinking it's the same as my other question, I'm asking this question because I'm trying to figure out if my reducer USING immutability helper is messing up my Firebase database, so I'm trying to figure out how to write the reducer WITHOUT using immutability helper so i can help eliminate what my bug is.

2

2 Answers 2

1

Use spread operator, and write it like this:

case types.REMOVE_PAGE_FROM_PLAYLIST: {    
    let playlistCopy = [...(state.playlistDict[ action.playlistId ].pages)];
    playlistCopy.splice( action.pageIndex, 1 );

    return {
        ...state,
        playlistDict: {
            ...state.playlistDict,
            [action.playlistId]: {
                ...state.playlistDict[action.playlistId],
                pages: playlistCopy
            }
        }
    }
}
1
  • "let playlistCopy = [...(state.playlistDict[ action.playlistId ].pages)];" my IDE doesn't like the syntax of that line Commented Aug 29, 2017 at 6:07
1

Using Object Spread Operator:

case types.REMOVE_PAGE_FROM_PLAYLIST: {
  return {
    ...state,
    playlistDict: {
      ...state.playlistDict,
      [action.playlistId]: {
        ...state.playlistDict[action.playlistId],
        pages: [...state.playlistDict[action.playlistId].pages].splice(action.pageIndex, 1)
      }
    }
  }
}
2
  • this one deleted all the pages for some reason.. the pages property was null Commented Aug 29, 2017 at 6:21
  • 1
    Sorry, i miss .pages. in last line. Now it should work well Commented Aug 29, 2017 at 6:25

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.