X
X
xXRustamXx2018-11-23 20:05:18
React
xXRustamXx, 2018-11-23 20:05:18

Is it correct to update state in redux this way?

There is the following state:

const state = {
  desks: [
    {
      id: 1,
      name: 'Что нужно сделать',
      cards: [
        {
          id: 1,
          name: 'Lol kek cheburek'
        }
      ]
    }
  ]
};

And reducer:
function deskReducer(state = [], action) {
  switch(action.type) {
    case 'ADD_CARD':
      let desks = state.slice();
      let currentDesk = desks.filter( (item) => item.id === action.id )[0];
      currentDesk.cards.push({
        id: currentDesk.cards.length + 1,
        name: action.name
      });
      return desks;
    default: 
      return state;
  }
}

I was alerted that after the push in the reducer, not only the desks variable is updated, but also the state is also updated before the state is returned, the code works, but nevertheless I copied the array and the changes were applied as if I didn’t do it at all, what is it connected with and is it possible way to update state?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question