'How to delay updating React state in react-swipeable-list?
I'm trying to use react-swipeable-list to enable swiping in a pair of lists (the first is a list of items I might shop for, the second list is the list of stuff I'm shopping for the next time I go to the store).
I'm using this as part of a React app.
I notice that when I have an event handler for swiping that only console.log's a message then things work great. I see the message, the swiped item smoothly slides back into place, and things look the way that I'd like them to.
However, if the event handler for the swiping modifies the app's (React) state then the swiped list item 'snaps back' and the new item shows up instantaneously in the second list.
I believe what's happening is that the state change is causing a re-render immediately, which is why things snap back/appear instantaneously - React isn't waiting for the swiping animation to finish sliding the list item back to it's original place and instead re-renders the whole page.
I've looked through the react-swipeable-list docs (and code) and there doesn't appear to be a callback for when the animation has finished (nor am I clear on how to add such a thing).
I looked online for general techniques for running JS code when a CSS animation is finished and it looks like it can be done by adding an event listener to the DOM element that's being animated. My understanding is that React code isn't supposed to interact with DOM elements directly (because React will move/re-render/delete them, I think).
Is there a way to tell react-swipeable-list to finish it's animation before running the event handler for swiping an item?
Solution 1:[1]
As a hack one can use window.setTimeout
to run the code after the animation has finished, although this feels fragile and error-prone.
Does anyone have a better solution? Hopefully? :)
Solution 2:[2]
You can check this version of the lib - there is a configurable callback delay: https://github.com/marekrozmus/react-swipeable-list#destructivecallbackdelay
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | MikeTheTall |
Solution 2 | Marek R. |