Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from a nested array without using Immutability Helper

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.

like image 908
user1189352 Avatar asked Jun 05 '26 06:06

user1189352


1 Answers

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
            }
        }
    }
}
like image 148
Mayank Shukla Avatar answered Jun 06 '26 21:06

Mayank Shukla