4

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.

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

6 Comments

I want to change first object in array, i tried this: return [...Object.assign({}, state[0], {show:true} ), ...slice(1,5)] It return just last 4 objetcs, first is missing...
It should be ...state.slice in your case.
Still the same, it returns just 4 elements, first that i want to mutate is not in returned array... :(
Don't specify a length in your splice. Look at my example, just use ...state.slice(1) to get the remaining array items.
It works now, i remove spread operator before Object.assign, looks like it is unnecessary. return [Object.assign({}, state[0], {show:true} ), ...state.slice(1)]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.