I want to do infinite slider in React Native, but Animated.Scrolview, "scrollTo" function gets error

19 views Asked by At

In my slider, I want to go to top slide after last slide scrolled. but my code got an error: "Maximum call size exceeded". Because scrollTo function runs in every pixel when scrolling. This is my code:

const Slider = ({ data, SliderItemComponent, sizeMinus, dotColor, paginationInside, infiniteLoop }: SliderProps) => {
  const { width } = Dimensions.get('screen');
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const scrollViewRef = useAnimatedRef<any>();
  const sizeMinusValue = sizeMinus ?? 50;
  const SIZE = width - sizeMinusValue;
  const xCoordinate = useSharedValue(0);
  const overflow = paginationInside ? 'hidden' : 'visible';
  const infiniteData = infiniteLoop ? [ ...data, ...data ] : data;
  const SNAP_WIDTH = SIZE + spacing.xs
  const optimizationValueForIndexCount = sizeMinus ? (50 - sizeMinus) : 0
  let scrollTotop = true

  const onScroll = useAnimatedScrollHandler({
    onScroll: (event) => {
      'worklet'
      xCoordinate.value = event.contentOffset.x;

      const currentIndex = Math.floor(xCoordinate.value / (SNAP_WIDTH + optimizationValueForIndexCount));

      console.log('out: ', scrollTotop);

      if (currentIndex === data.length - 1 && infiniteLoop && scrollTotop) {

          scrollTo(scrollViewRef,0,SIZE, true)
          scrollTotop = false
          console.log('in if clouse: ', scrollTotop);

      }
    }
  });

  return (
    <View>
      <View style={[ $container, { overflow } ]}>
        <Animated.ScrollView
          horizontal
          bounces={false}
          decelerationRate="fast"
          onScroll={onScroll}
          ref={scrollViewRef}
          scrollEventThrottle={16}
          showsHorizontalScrollIndicator={false}
          snapToAlignment={'center'}
          snapToInterval={SNAP_WIDTH}
          style={$scrollStyle}
        >
          {infiniteData.map((item, index) => (
            <SliderItemComponent index={index} item={item} key={index} />
          ))}
        </Animated.ScrollView>

also this is my console.log: log

I tried to prevent with scrollTotop boolean value but it did not work. How can I prevent scrollTo function call loop ?

0

There are 0 answers