Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace array item with another one without mutating state

This is how example of my state looks:

const INITIAL_STATE = {
 contents: [ {}, {}, {}, etc.. ],
 meta: {}
}

I need to be able and somehow replace an item inside contents array knowing its index, I have tried:

      return {
        ...state,
        contents: [
          ...state.contents[action.meta.index],
          {
            content_type: 7,
            content_body: {
              album_artwork_url: action.payload.data.album.images[1].url,
              preview_url: action.payload.data.preview_url,
              title: action.payload.data.name,
              subtitle: action.payload.data.artists[0].name,
              spotify_link: action.payload.data.external_urls.spotify
            }
          }
        ]
      }

where action.meta.index is index of array item I want to replace with another contents object, but I believe this just replaces whole array to this one object I'm passing. I also thought of using .splice() but that would just mutate the array?

like image 340
Ilja Avatar asked Feb 12 '16 12:02

Ilja


People also ask

How do you splice an array without mutating the original array?

Steps : Create the clone of the array using the spread operator or slice method. apply the splice method on the cloned array and return the extracted array.


1 Answers

Note that Array.prototype.map() (docs) does not mutate the original array so it provides another option:

 const INITIAL_STATE = {
   contents: [ {}, {}, {}, etc.. ],
   meta: {}
 }

 // Assuming this action object design
 {
   type: MY_ACTION,
   data: {
     // new content to replace
   },
   meta: {
     index: /* the array index in state */,
   }
 }

 function myReducer(state = INITIAL_STATE, action) {
   switch (action.type) {
     case MY_ACTION: 
       return {
         ...state,
         // optional 2nd arg in callback is the array index
         contents: state.contents.map((content, index) => {
           if (index === action.meta.index) {
             return action.data
           }

           return content
         })
       }
   }
 }
like image 139
Sia Avatar answered Sep 24 '22 04:09

Sia