Mireia
Mireia

Reputation: 333

Recording user interactions in React Native / Snap Carousel - firstItem

I have been having this issue for a couple of days and cannot seem to find a solution.

I would like to record the user's interaction on a database. I am displaying data using a React Native Snap Carousel, and need to record if the item was viewed by the user. To do this, and as described in other stack overflow questions, I am using "onSnapToItem". onSnapToItem is triggered everytime I change from one slide to another. Then, if the user views the slide for more than 2 seconds, I count that as an interaction.

The problem is that onSnapToItem is not triggered on the firstItem (which makes sense, because I am not changing slide). Can anybody think of a solution?

      <Carousel
              vertical
              layout={"default"}
              ref={_carousel}
              data={promos}
              renderItem={_renderItem}
              autoplay={true}
              autoplayInterval={4000}
              onSnapToItem = { (index) => {
                clearTimeout(writeDelay)
                writeDelay=setTimeout (()=>{
                  console.log(promos[index].id)
                },2000)
                }}
              onEndReached={_retrieveMore}
              />

Upvotes: 0

Views: 1394

Answers (2)

silvia zulinka
silvia zulinka

Reputation: 731

you can use this library @svanboxel/visibility-sensor-react-native

Upvotes: 0

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Programmatically snap to item on screen focus.

componentDidMount() {
  setTimeout(() => this._carousel.snapToItem(0), 1000);

  // if above code doesn't work then you can try is for first item
  writeDelay=setTimeout (()=>{
     console.log(promos[0].id); // index here is 0 for first item
  },1000)
}

...

render() {
  <Carousel
    ...
    ref={c => { this._carousel = c }}
  />
}`

Upvotes: 1

Related Questions