Error in Carousel React-Native

Asked

Viewed 23 times

0

Good People, I’m trying to implement Carousel using React-Native-Anchor-Carousel, when I do with still images, I create an array by passing the images and it works 100%, but when fetching these images via api, even receiving a structure similar to the one I already have right in the code I get an error:

Invariant Violation: scrollToIndex out of range: requested index 2 but Maximum is 1

made a console.log, and I realize that my request is called twice, follows my code for analysis.

OBS. is React-Native ~0.63.4

import * as React from 'react';
import { StyleSheet, TouchableOpacity, Dimensions, ImageBackground, Text, View} from 'react-native';
import Carousel from 'react-native-anchor-carousel'; 
import axios from 'axios'
import { convertCompilerOptionsFromJson } from 'typescript';


const width = Dimensions.get('window').width;

export default class ImageCarrousel extends React.Component{

  state = {
    Slides: [],
    init:0,
  }

  loadSlides = () =>{
    axios.get('http://174.138.0.164/api/slides').then(response => { 
      this.setState({ Slides: response.data, init:1 })
    }).catch(() => { 
      console.log('Error retrieving data')
    })
  }

  componentDidMount() {
    this.loadSlides();
  }

  renderItem = ({ item, index}) => {
      const { image, link, title } = item;
      return (
          <TouchableOpacity
            activeOpacity={1}
            style={styles.item}
            onPress={() => {
              this.numberCarousel.scrollToIndex(index);
            }}
          >
            <ImageBackground source={{ uri: image }} style={styles.imageBackground}/>
          </TouchableOpacity>
      );
  };
  render() {
    console.log(this.state.Slides);
      return (
        <Carousel
          style={styles.carousel}
          data={this.state.Slides}
          renderItem={this.renderItem}
          itemWidth={0.8 * width}
          inActiveOpacity={0.8}
          inActiveScale={0.93}
          containerWidth={width - 2}
          separatorWidth={0}
          initialIndex={2}
          ref={(c) => {
            this.numberCarousel = c;
          }}
        />
      );
    }
}

const styles = StyleSheet.create({
  carousel: {
    flex: 1,
    backgroundColor: '#fff'
  },
  item: {
    borderWidth: 0,
    backgroundColor: 'white',
    flex: 1,
    borderRadius: 0,
    elevation: 2
  },
  imageBackground: {
    flex: 2,
    backgroundColor: '#EBEBEB',
    borderWidth: 0,
    borderColor: 'white',
    padding: 5
  }
});
  • 1

    It’s hard to understand the code, but this one initialIndex={2}, would not be initialIndex={this.state.init}?

  • That’s right @Cmtecardeal Thanks so much for your help!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.