Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i properly clone json array in redux?

Im new in Redux and Redux concepts look weird for me at first. Let say i have an array in redux state.

const state = [ 
  {show: false, id : '1'},
  {show: false, id : '2'},
  {show: false, id : '3'},
  {show: false, id : '4'},
  {show: false, id : '5'}
]

I want to clone this array and change/mutate one object.

I tried something like this in reducer but it did not work.

   return  [...state.concat(Object.assign({}, state[0], {show:true} )).slice(1,5)];

Any help or explanation would be nice.

like image 653
TariqN Avatar asked Sep 19 '16 22:09

TariqN


1 Answers

I think you might have switched [] with {} in your question.

Assuming your state is:

const state = [ 
  { show: false, id: '1' },
  { show: false, id: '2' },
  { show: false, id: '3' },
  { show: false, id: '4' },
  { show: false, id: '5' }
]

You can write a reducer like this:

return [
  ...state.slice(0, index),
  Object.assign({}, state[index], { /* your changes */ })
  ...state.slice(index + 1)
]

Where index is the index of the element you want to change.

References

  • Redux: Avoiding Array Mutations with concat(), slice(), and ...spread
like image 165
Mario Tacke Avatar answered Sep 24 '22 17:09

Mario Tacke