usaidather / carouselView

34 stars 31 forks source link

Problems with dynamic data obtained by axios #1

Open jnovoalujan1 opened 4 years ago

jnovoalujan1 commented 4 years ago

Hello, in advance thank you very much for the publication of your code, it has helped me a lot, however I present a problem when the data is dynamic. I'm getting the data from an API but this presents me with the following problem:

Scroll to the next image but always return to the first image, jump to the second image, then return to the first image, then jump to the third image and then jump to the first image, and then jump to the fourth image, it is not scrolling from the first to the second and then the third and fourth, before passing, you are in the first, do you know why I am getting this behavior?

I share only the file where I am obtaining the data, since the rest is equal to its code.

I hope you can help me.

HomeScreen.js

import React, { useEffect, useState } from "react";
import { View } from "react-native";
import CategoriesScreen from "./Categories/CategoriesScreen";
import { ScrollView } from "react-native-gesture-handler";
import Carousel from "./Banner/BannerOficial";
import { axiosClient } from "../../config/axios";

export default function HomeScreen({ navigation }) {

  const [banners, setBanners] = useState([]);

  useEffect(() => {
    getBannersAPI();
  }, []);

  function getBannersAPI(){
    axiosClient
    .get("/service/banner_available")
    .then(async function (response) {
      setBanners(response.data);
    })
    .catch(function (error) {
      console.log("Error cargando los banners: ", error);
    });
  }

  return (
    <View style={{ flex: 1 }}>
      <ScrollView>
        <Carousel data={banners} />
        <CategoriesScreen navigation={navigation} />
      </ScrollView>
    </View>
  );
}

BannerOficial.js

import React, { useState, useEffect } from 'react'
import { View, Text, StyleSheet, Dimensions, FlatList, Animated } from 'react-native'
import CarouselItem from './BannerItem'

const { width, heigth } = Dimensions.get('window')
let flatList

function infiniteScroll(dataList){
    const numberOfData = dataList.length
    let scrollValue = 0, scrolled = 0

    setInterval(function() {
        scrolled ++
        if(scrolled < numberOfData)
        scrollValue = scrollValue + width

        else{
            scrollValue = 0
            scrolled = 0
        }

        this.flatList.scrollToOffset({ animated: true, offset: scrollValue})

    }, 3000)
}

const Carousel = ({ data }) => {
    const scrollX = new Animated.Value(0)
    let position = Animated.divide(scrollX, width)
    const [dataList, setDataList] = useState(data)

    useEffect(()=> {
        setDataList(data)
        infiniteScroll(dataList)
    })

    if (data && data.length) {
        return (
            <View>
                <FlatList data={data}
                ref = {(flatList) => {this.flatList = flatList}}
                    keyExtractor={(item, index) => 'key' + index}
                    horizontal
                    pagingEnabled
                    scrollEnabled
                    snapToAlignment="center"
                    scrollEventThrottle={16}
                    decelerationRate={"fast"}
                    showsHorizontalScrollIndicator={false}
                    renderItem={({ item }) => {
                        return <CarouselItem item={item} />
                    }}
                    onScroll={Animated.event(
                        [{ nativeEvent: { contentOffset: { x: scrollX } } }]
                    )}
                />

                <View style={styles.dotView}>
                    {data.map((_, i) => {
                        let opacity = position.interpolate({
                            inputRange: [i - 1, i, i + 1],
                            outputRange: [0.3, 1, 0.3],
                            extrapolate: 'clamp'
                        })
                        return (
                            <Animated.View
                                key={i}
                                style={{ opacity, height: 10, width: 10, backgroundColor: '#595959', margin: 8, borderRadius: 5 }}
                            />
                        )
                    })}

                </View>
            </View>
        )
    }

    console.log('Please provide Images')
    return null
}

const styles = StyleSheet.create({
    dotView: { flexDirection: 'row', justifyContent: 'center'}
})

export default Carousel

BannerItem.js

import React from "react";
import { View, StyleSheet, Text, Image, Dimensions} from 'react-native';

const { width, height} = Dimensions.get('window')

const CarouselItem = ({item}) => {
    return(
        <View style={styles.cardView}>
            <Image style={styles.image} source = {{ uri: item.imagePath}}/>
        </View>
    )
}

const styles = StyleSheet.create({
    cardView:{
        flex:1,
        width: width -20,
        height: height / 7,
        backgroundColor: "white",
        margin: 10,
        borderRadius: 10,
        shadowColor: "#000",
        shadowOffset: {width: 0.5, height: 0.5},
        shadowOpacity: 0.5, 
        shadowRadius: 3,
        elevation: 5,
    },
    image: {
        width: width-20,
        height: height / 3,
        borderRadius: 10
    }
})

export default CarouselItem

axios.js

import axios from 'axios';

const axiosClientLogin = axios.create({
  baseURL: 'http://192.168.1.10:8080',
  headers: {
    'Content-Type':'application/x-www-form-urlencoded',
    "Authorization" : `Basic aWRfY2xpZW50ZToxMjM0NQ==`
  }
});

const axiosClientFormData = axios.create({
  baseURL: 'http://192.168.1.3:8080',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

const axiosClient = axios.create({
  baseURL: 'http://192.168.1.10:8080'
});

export {axiosClientLogin, axiosClient, axiosClientFormData};

It should be noted that when I have static data as you have in the youtube video, it works well. but with dynamic data obtained from the api it presents the problem that I tell you

usaidather commented 4 years ago

Hello, Thanks for your email, it should work normally, you might have missed something... I cant help you by looking at this code... Can you share your complete code

Thanks.

On Wed, Jun 3, 2020, 10:33 PM julianlujan1 notifications@github.com wrote:

Hello, in advance thank you very much for the publication of your code, it has helped me a lot, however I present a problem when the data is dynamic. I'm getting the data from an API but this presents me with the following problem:

Scroll to the next image but always return to the first image, jump to the second image, then return to the first image, then jump to the third image and then jump to the first image, and then jump to the fourth image, it is not scrolling from the first to the second and then the third and fourth, before passing, you are in the first, do you know why I am getting this behavior?

I share only the file where I am obtaining the data, since the rest is equal to its code.

I hope you can help me.

import React, { useEffect, useState } from "react"; import { View } from "react-native"; import CategoriesScreen from "./Categories/CategoriesScreen"; import { ScrollView } from "react-native-gesture-handler"; import Carousel from "./Banner/BannerOficial"; import { axiosClient } from "../../config/axios";

export default function HomeScreen({ navigation }) {

const [banners, setBanners] = useState([]);

useEffect(() => { getBannersAPI(); }, []);

function getBannersAPI(){ axiosClient .get("/service/banner_available") .then(async function (response) { setBanners(response.data); }) .catch(function (error) { console.log("Error cargando los banners: ", error); }); }

return ( <View style={{ flex: 1 }}>

</View>

); }

It should be noted that when I have static data as you have in the youtube video, it works well. but with dynamic data obtained from the api it presents the problem that I tell you

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/usaidather/carouselView/issues/1, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABLLGWKE5M2XH2RRONVOKIDRU2CM3ANCNFSM4NR36RKA .

jnovoalujan1 commented 4 years ago

Thanks for responding so soon, edit the issue and add the code from the other files.

jnovoalujan1 commented 4 years ago

any solution to this problem? @usaidather

usaidather commented 4 years ago

You did not share your code with me

On Tue, Jun 9, 2020, 7:06 PM julianlujan1 notifications@github.com wrote:

any solution to this problem?

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/usaidather/carouselView/issues/1#issuecomment-641320876, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABLLGWOIZPSXR63YOIJD24LRVY6X5ANCNFSM4NR36RKA .

jnovoalujan1 commented 4 years ago

@usaidather update the edition with all the code I use

usaidather commented 4 years ago

Ok i will chevk if i get some time

On Tue, Jun 9, 2020, 7:35 PM julianlujan1 notifications@github.com wrote:

@usaidather https://github.com/usaidather update the edition with all the code I use

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/usaidather/carouselView/issues/1#issuecomment-641338487, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABLLGWJ5VFX4F5YRW4AREFTRVZCDHANCNFSM4NR36RKA .

jnovoalujan1 commented 4 years ago

@usaidather I would really appreciate it, since your carousel is just what I need and even better that it is written with hooks. In the issue is all the code, thanks in advance for responding.

usaidather commented 4 years ago

Just remind me at the weekend as well in case if I forgot.

On Tue, Jun 9, 2020, 8:12 PM julianlujan1 notifications@github.com wrote:

@usaidather https://github.com/usaidather I would really appreciate it, since your carousel is just what I need and even better that it is written with hooks. In the issue is all the code, thanks in advance for responding.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/usaidather/carouselView/issues/1#issuecomment-641361319, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABLLGWPACD5DSRGXOVTBPJLRVZGMNANCNFSM4NR36RKA .

dhiresh1396 commented 3 years ago

Hello, I have been struggling to resolve the same issue for a few days now for me the problem was solved when I added a condition in the Infinite Scroll function


function infiniteScroll(dataList){
    const numberData = dataList.length
    let scrollValue = 0, scrolled = 0
if(numberData){
    setInterval(function() {
        scrolled ++
        if(scrolled < numberData)
        scrollValue = scrollValue + width
        else{
            scrollValue = 0
            scrolled = 0
        }
        this.flatList.scrollToOffset({ animated: true, offset: scrollValue})
    }, 3000)
}
}}