How can I update state in Redux - moving todo up and down - React

Viewed 139

I am trying to find out how can I update the state in redux so that I can move the elements up an d down on click.

state is an array of objects, currently 3 elements with id, text, and isCrossed: false. On click I am passing the id so action.id will be the id of the element I want to move.

My current code below but it does not work. It seem to only move once then the code breaks. Ive added if statement to avoid moving the first element up

case 'UP_TODO': {
     return state.map((todo, idx, arr) => {
        if (action !== arr[0]) {
          return (todo.id === action.id  ? arr[idx - 1] : todo.id === action.id - 1 ? arr[idx + 1] : todo)
        } else {
          return todo
        }
      });
      
    }
2 Answers

You can't mutate the array you are currently mapping over. You'll need to shallow copy the array first then swap the values at the specified indices.

case 'UP_TODO': {
  // compute todo index
  const index = state.findIndex(todo => todo.id === action.id);

  // if todo index is found and not first element,
  // and todos array has length 2 or more
  if (index > 0 && state.length > 1) {
    // shallow copy state
    const newState = [...state];

    // swap values at found index and index - 1
    [newState[index], newState[index - 1]] = [newState[index - 1], newState[index]];

    return newState;
  } else {
    // not swappable, return current state
    return state;
  }
}

Similarly for the move down case you will need to ensure there are at least 2 elements in the array and the found index isn't already the last element in the todos array.

i hope this method help you for creating new array:

function moveArrayItemToNewIndex(arr, old_index, new_index) {
    if (new_index >= arr.length) {
        var k = new_index - arr.length + 1;
        while (k--) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr; 
};
Related