React-id-swiper: on.slideChange doesn't recognize updates on the instance state set with useState hook

Created on 14 Mar 2019  路  2Comments  路  Source: kidjp85/react-id-swiper

I am currently implementing the newest version 2.1.0 of react-id-swiper. I need to tell an external tool the current slide index every time the slides change. Therefore I am following the documentation to use the getSwiper prop to store the swiper instance in the component state using the useState hook and then send swiper.realIndex to the outside:

function MySwiper({ onSwipeChange }) {
  const [swiper, updateSwiper] = useState(null);

  const params = {
    // ...
    getSwiper: updateSwiper,
    on: {
      slideChange: () => {
        onSwipeChange(swiper.realIndex);
      }
    }
    // ...
  };

  return (
    <Swiper {...params}>
      // ...
    </Swiper>
  );
}

When I log out the swiper variable right before the return statement, it is null for the first render cycle and a proper Swiper instance for the second render cycle, when it has mounted. So the state seems to be correctly set.

Anyway, inside the slideChange callback the swiper state variable seems to be fixed to null. The callback never receives the instance.

Am I missing something or can I do it differently?

Most helpful comment

Hi @devbucket , there are 2 ways to add event listener to Swiper.

  1. Using on parameter on swiper initialization
  2. Using on method after swiper initialization.

In your case, the first method won't work because swiper instance is always null initial render. We can achieve by the second one by using useEffect like below

const [currentIndex, updateCurrentIndex] = useState(0)

useEffect(
    () => {
      if (swiper !== null) {
        swiper.on("slideChange", () => updateCurrentIndex(swiper.realIndex));
      }
    },
    [swiper]
  );

Here is the working demo

All 2 comments

Hi @devbucket , there are 2 ways to add event listener to Swiper.

  1. Using on parameter on swiper initialization
  2. Using on method after swiper initialization.

In your case, the first method won't work because swiper instance is always null initial render. We can achieve by the second one by using useEffect like below

const [currentIndex, updateCurrentIndex] = useState(0)

useEffect(
    () => {
      if (swiper !== null) {
        swiper.on("slideChange", () => updateCurrentIndex(swiper.realIndex));
      }
    },
    [swiper]
  );

Here is the working demo

Great! That works! Thanks so much!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

maheshambiga picture maheshambiga  路  4Comments

xinconan picture xinconan  路  6Comments

d4n1b picture d4n1b  路  5Comments

trevans24 picture trevans24  路  6Comments

mbenjrinija picture mbenjrinija  路  4Comments