21

I am reading an example of the React-dnd project:

moveCard(dragIndex, hoverIndex) {
    const { cards } = this.state;
    const dragCard = cards[dragIndex];

    this.setState(update(this.state, {
      cards: {
        $splice: [
          [dragIndex, 1],
          [hoverIndex, 0, dragCard]
        ]
      }
    }));}

Is this $splice the same one explained on this page?

Could anybody explain what does this chunk of code do? The $splice function is very confusion to me.

Cheng
  • 16,824
  • 23
  • 74
  • 104

2 Answers2

23

It's basically an immutable version of plain splice functions such as

newcards.splice(dragIndex, 1); // removing what you are dragging.
newcards.splice(hoverIndex, 0, dragCard); // inserting it into hoverIndex.

Instead of directly manipulating the target array, those Immutability Helpers are helping you update the state by creating and assigning a new state.

goodhyun
  • 4,814
  • 3
  • 33
  • 25
6

Took me a while to understand. Here is step by step explanation in conventional arrow function

  moveCard = (dragIndex, hoverIndex) => {
    // list of cards
    let newcards = this.state.cards; 

    // dragCard is card we are dragging
    let dragCard = newcards[dragIndex]; 

   // removing this dragCard from array
    newcards.splice(dragIndex, 1);

     // insert dragCard at hover position
    newcards.splice(hoverIndex, 0, dragCard); 

    // update State
    this.setState({
      cards: newcards
    });
  };
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154