Slbox
Slbox

Reputation: 13108

How to add items to an array in Redux?

I'm building an Electron application and I'm trying to keep an array of images that are on each page so if the page is deleted I can easily delete all the associated images from the filesystem.

What I have now:

const initialState = [{
  uuid: '65ec81f5-a783-4abd-bd0d-1451adda58c6',
  imageUUIDs: []
}];

const actionsMap = {
   [ActionTypes.ADD_IMAGE_TO_PAGE](state, action) {
        const pageUUID = action.pageUUID;
        const imgUUID = action.imgUUID;
        return state.map(page =>
          (page.uuid === pageUUID ?
            Object.assign({}, page, {
              imageUUIDs: page.imageUUIDs.splice(0, 0, imgUUID),
            }) : page)
        );
  },

};

This initially seems to work when viewed at runtime, but I end up with an empty array after completion. What is the right way to maintain a list like this?

Upvotes: 0

Views: 385

Answers (1)

Adam Recvlohe
Adam Recvlohe

Reputation: 333

Use Array.prototype.concat instead of Array.prototype.splice. Array.prototype.concat returns a new array whereas Array.prototype.splice modifies the original array but does not return a new array, which is not what you are expecting.

Upvotes: 1

Related Questions