nuka-carousel icon indicating copy to clipboard operation
nuka-carousel copied to clipboard

Carousel goes into swing state when we control the slideIndex

Open varenya opened this issue 8 years ago • 10 comments

Bugs and Questions

Describe Your Environment

  • What version of nuka-carousel are you using? - 4.4.0
  • What version of React are you using? - 16.4.0
  • What browser are you using?- Chrome
  • What machine are you on? - MacBook

Describe the Problem

When we take over the control for setting the index and call the afterSlide callback in the latest version its causing the slideIndex to go in a swing state, heres the reproduction of the issue:

https://wny44o8jpl.codesandbox.io/ https://codesandbox.io/s/wny44o8jpl

Click on left/right couple of times and you will see that the slide index goes back and forth b/w two values causing the carousel to move left right in a loop.

Expected behavior: [What you expect to happen] - should behave normally as in there shouldn't be any swinging effect.

Actual behavior: [What actually happens] - There is a swinging effect.

Additional Information

Any additional information, configuration or data that might be necessary to reproduce the issue.

varenya avatar Sep 21 '18 05:09 varenya

@sarmeyer Can this be taken up as high priority? I think its because of the recent setTimeout changes to call the afterSlide which is causing this issue.

varenya avatar Sep 21 '18 05:09 varenya

I am having the same issue. I found a temporary fix to the issue:

afterSlide={slideIndex => {
  if (slideIndex === this.state.slideIndex) {
    this.setState({ slideIndex });
  }
}}

lukeliasi avatar Sep 21 '18 16:09 lukeliasi

same issue here :(

hamedmam avatar Sep 21 '18 16:09 hamedmam

@varenya : Hi, the recent timeout changes was to support afterSlide and beforeSlide to be called respect to their transitions.

I figured the issue was because setting the slideIndex in props as well as in afterSlide vs its transition speed. Some solution that worked are

  • setting afterSlide to something like afterSlide = {() => this.setSlideIndex()}
  • changing the speed prop value

Needs more investigation to do make it work without breakChanges. Please feel free to open a PR if you have any interesting solution. Thank you for this interesting find.

ashika01 avatar Sep 21 '18 21:09 ashika01

I encountered the same issue, and realized it happens when you update the slideIndex faster than the carousel's transition speed, by either swiping or any other control (dots, next/prev).

My solution involved

  1. Using the beforeSlide callback to update the parent state
  2. Maintain a boolean in the parent state, to enable/disable the dot-nav click, while the carousel is transitioning.

My solution looks like:

import React, { PureComponent } from 'react';
import Carousel from 'nuka-carousel';
import DotNav from 'app/components/dot-nav';

class CarouselWithDotNav extends PureComponent {
  state = {
    slideIndex    : 0,
    changingSlide : false,
  };

  handleDotClick = ({ index }) => {
    if (index !== this.state.slideIndex) {
      this.setState({ changingSlide : true, slideIndex : index });
    }
  }

  handleBeforeSlide = (slideIndex, endSlide) => {
    this.setState({
      changingSlide : true,
      slideIndex    : endSlide,
    });
  }
  
  handleAfterSlide = () => {
    this.setState({
      changingSlide : false,
    });
  }

  render() {
    const { children } = this.props;
    const { changingSlide } = this.state;

    return [
      <Carousel
        key="slider"
        autoplay
        slideIndex={this.state.slideIndex}
        beforeSlide={this.handleBeforeSlide}
        afterSlide={this.handleAfterSlide}
      >
        {children}
      </Carousel>,
      <DotNav
        key="dotnav"
        clickHandler={changingSlide ? () => null : this.handleDotClick}
        itemCount={React.Children.count(this.props.children)}
        currentIndex={this.state.slideIndex}
      />,
    ];
  }
}

export default CarouselWithDotNav;

tol-is avatar Sep 26 '18 14:09 tol-is

This issue has been addressed in the closed issue #427 as well. In the next release we take care of this in the Nuka-Carousel api. But for releases <=4.4.1 you can refer to this issue or issue #427 for pretty good solutions to the problem. Thank you everyone for chiming in, giving solutions and perspective on this bug. It was instrumental in getting this figured out for the upcoming release. Happy coding!!!

ElreyB avatar Oct 27 '18 16:10 ElreyB

slideIndex in the afterSlide method ends up NaN after the transition. Worked around the issue:

<Carousel
  slideIndex={this.state.slideIndex}
  afterSlide={(slideIndex) => {
    if (!Number.isNaN(slideIndex)) {
      this.setState({ slideIndex });
    }
  }}
>
...

olduf avatar Dec 18 '18 15:12 olduf

slideIndex in the afterSlide method ends up NaN after the transition. Worked around the issue:

<Carousel
  slideIndex={this.state.slideIndex}
  afterSlide={(slideIndex) => {
    if (!Number.isNaN(slideIndex)) {
      this.setState({ slideIndex });
    }
  }}
>
...

same issue, reproduced here https://codesandbox.io/s/lrjzmmywnl

it appears afterSlide slideIndex throws a NaN for some reason, but if I keep track of a ref to the Carousel(this.carousel.current.state.currentSlide) it's the correct slideIndex, always.

toklok avatar Jan 10 '19 17:01 toklok

I've had to fix a case where I wanted to use an external slideIndex to be able to add an onClick event to each image that would move the carousel to that image.

What happened to me was not that it swinged, but sometimes clicking didn't work. What I found out was that the props.slideIndex and state.currentSlide sometimes were not in sync. React does not recommend having two sources of truth (props and state), but it seems that in this case it was needed since it was important to support both internal and external control. Even so, I think I stumbled upon one of the pieces of code where this desynchronization might be happening.

This is a snippet of the index.js, starting on line 106:

  componentWillReceiveProps(nextProps) {
    const slideCount = getValidChildren(nextProps.children).length;
    const slideCountChanged = slideCount !== this.state.slideCount;
    this.setState(prevState => ({
      slideCount,
      currentSlide: slideCountChanged
        ? nextProps.slideIndex
        : prevState.currentSlide
    }));

    if (slideCount <= this.state.currentSlide) {
      this.goToSlide(Math.max(slideCount - 1, 0), nextProps);
    }

First of all, componentWillReceiveProps will be deprecated, so we might want to migrate to getDerivedStateFromProps.

Secondly, setState is an asynchronous function, so the changes to state are not immediate, even though we are trying to use the updated state right after using setState, and this might cause desynchronization problems between props.slideIndex and state.currentSlide.

I was able to work around this by double checking if this desync happened on my external controls.

So whenever I modified my external state, on the callback of my setState I added an if clause to check whether there was some desync, and if there was, I manually corrected it.

this.setState({
  currentSlide: index,
  isTransitioning: true
}, () => {
  if(this.state.currentSlide !== this.carousel.current.state.currentSlide) {
    this.carousel.current.setState({
      currentSlide: this.state.currentSlide
    })
  }
})

I'm well aware that this is just a workaround, and it's not recommended to do this, It would be good to rewrite some of the code to avoid this desync problems, and avoid using two sources of truth whenever possible, if I get some free time I'll try to make a PR to fix it.

juanmardefago avatar Mar 13 '19 21:03 juanmardefago

I'm unable to reproduce this issue in the most recent version v4.6.3 - if it's still an issue, please reopen with updated codesandboxes. Thank you!

sarmeyer avatar Feb 20 '20 17:02 sarmeyer