DEV Community

Arash Jangali
Arash Jangali

Posted on

Implementing the Swipe Card Undo Functionality: My Thought Process

Day 94 of #100DaysOfCode: Still working on the undo functionality. I think I'm almost there with the logic. The problem is just that nothing happens when I press the undo button (😬). But don't worry, I am using useRef and useMemo to create a reference for every card at the specific index so that the last card can be fetched and removed from the "liked users" array back to the "new users" array. In this blog post, I will explain how I am implementing the undo functionality and my thought process behind it.

When building the swipe card feature, the undo button is an essential feature that allows users to revert a swipe action. However, it's not as straightforward as it may seem to implement it. The basic concept of the undo button is to move the card from the 'liked users' array back to the 'new users' array.

To implement the undo functionality, I first created an array to store the references to each card. I achieved this by using the useMemo hook, which ensures that the reference array is only created once when the component is first mounted.

Next, I created a state variable called currentIndex, which tracks the current index of the card that is being swiped. I then created a useRef hook called currentIndexRef, which is used to store the current index.

To handle the undo button's logic, I created a function called handleUndo, which is called when the undo button is clicked. The handleUndo function first checks if the undo button is active by comparing the currentIndex to the length of the notLikedClients array. If the undo button is not active, the function returns. Otherwise, it increases the currentIndex by one and updates the currentIndexRef.

Finally, the restoreCard function is called on the last card in the notLikedClients array. This function restores the card back to its original position by animating it back into the card stack.

By the way, I did some research on implementing the undo function and came across this helpful resource:

https://github.com/3DJakob/react-tinder-card-demo/blob/master/src/examples/Advanced.js

Top comments (0)