0

I was Going through This Medium article on how to update a state array in Redux reducer. The writer, when appending and prepending actions are dispatched is simply assigning a new array to todos and inside that using spread operator to copy the contents of current state todos array which contains objects inside it . Since the spread operator does shallow copying isn't the original reference of the object-in-memory is being passed/copied inside the new todos array Or I am mistaken in my Concept. If I am right then what is the right way to do this.

Any help will be greatly appreciated.

state

 const state = { 
    todos: [
      {
       username: "test",
       id: 1,
       title: "Eat",
       completed: true
      },
      {
       username: "test",
       id: 2,
       title: "Code",
       completed: false
      },
      {
       username: "test",
       id: 3,
       title: "Sleep",
       completed: false
      }
     ]
    }; 

 see in the action PREPEND_TODO inside todos while doing ...state.todos writer is spreading the reference of objects instead of new todos array not actual copying the content of that object.

    const reducer = (state, action) => {
     swicth(action.type){
      case PREPEND_TODO: 
       return { // returning a copy of orignal state 
        ...state, //spreading the original state
        todos: [action.payload, ...state.todos] // new todos array
       }
    case APPEND_TODO: 
      return { // returning a copy of orignal state 
       ...state, //copying the original state
       todos: [...state.todos, action.payload] //new todos array 
      }
      default: return state;
     }
    }

https://medium.com/swlh/few-ways-to-update-a-state-array-in-redux-reducer-f2621ae8061#:~:text=First%2C%20we%20will%20find%20the,todos%20to%20that%20new%20array.

0 Answers0