davidjerleke / embla-carousel

A lightweight carousel library with fluid motion and great swipe precision.
https://www.embla-carousel.com
MIT License
5.94k stars 180 forks source link

[Bug]: First slide is lagging when using infinite scroll and slides with initial value of null #710

Closed j3sch closed 7 months ago

j3sch commented 8 months ago

Version

8.0.0-rc19

CodeSandbox

https://codesandbox.io/p/sandbox/embla-carousel-infinite-scroll-react-forked-lw364d?file=%2Fsrc%2Fjs%2FEmblaCarousel.tsx

What browsers are you seeing the problem on?

Firefox, Chrome

Steps to reproduce

The bug occurs when swiping from the second slide to the first slide. Then it does not swipe normally, but the swipe stops between the second and the first one.

Expected Behavior

That it scrolls back to the first slide normally.

Additional Context

I have slightly modified the infinite scroll example. I need to run a useEffect in the app to calculate the slides because I don't always start at index 0. The problem with this is that if the initial value of slides is null, the slider hangs when swiping from the second to the first slide. This error only occurs with the custom code for watchSlides for infinite scrolling.

 // works fine
  const [slides, setSlides] = useState<number[] | null>([0, 1, 2, 3, 4])

  // cause problems
  const [slides, setSlides] = useState<number[] | null>(null)

  // cause problems
  const [slides, setSlides] = useState<number[] | null>([])

  useEffect(() => {
    const SLIDE_COUNT = 5
    const SLIDES = Array.from(Array(SLIDE_COUNT).keys())
    setSlides(SLIDES)
  }, [])

I couldn't explain why it only hangs on one slide, but all the others run smoothly. Thanks for your time and creating this great library!

Which variants of Embla Carousel are you using?

Before submitting

j3sch commented 8 months ago

I now use slides with the initial value [0, 1] because this is the minimum number of slides I show.

When I look at my two slides, everything still works fine. However, when the useState updates the value of slides, for example with the value [0, 1, 2], something breaks. The swipe action from the second to the first slide becomes laggy. It briefly shows all three slides, then it reverts to the previous value, and I only see my two slides (I'm not sure if this is related to my code or if it's a related to the same issue).

Is it possible that I have to reload the embla engine or do something else after updating the value of the slides?

j3sch commented 7 months ago

I have refactored my code so that I don't use useEffect. Now I have no more problems.

https://react.dev/learn/you-might-not-need-an-effect