I'm trying to implement a slider in my react native app. I'm using the react-native-web-swiper library. I'm using the useState hook to monitor which index the swiper is on. In the onIndexChanged() prop of the swiper, I update the state (current index). My problem is that the onPress event for my swiper components doesn't use the updated state.
export default ({ navigation, route }: any) => { const pages = DataController.getData().onboardingPages; const swiper = useRef<Swiper>(null); const [index, setIndex] = useState<number>(0); const handleNextButton = () => { console.log("INDEX IN BUTTON PRESS", index); // index is zero here?? it should be 0,1,2, or 3 if (index !== pages.length - 1) { swiper.current?.goToNext(); } else { navigation.replace("Landing"); } }; useEffect(() => { console.log("useeffect called with index ", index); // index is correct here }, []); useLayoutEffect(() => { console.log("uselayouteffect called with index ", index); // index is correct here if (index !== pages.length - 1) { navigation.setOptions({ headerRight: () => (<Text style={styles.skip} onPress={() => navigation.replace("Landing")}> Skip</Text> ), }); } else { navigation.setOptions({ headerRight: undefined, }); } }, [index]); return (<Swiper ref={swiper} controlsProps={{ prevTitle: "", nextTitle: "", prevPos: false, nextPos: false, }} // controlsEnabled={false} loop={false} onIndexChanged={index => { console.log("index changed to ", index); setIndex(index); }}> {pages.map(item => { return (<OnboardingPage key={item.pageNumber} text={item.text} image={item.image} handleNextButton={handleNextButton} /> ); })}</Swiper> );};const styles = StyleSheet.create({ skip: { marginRight: 10, fontFamily: "an-regular", fontSize: 17, fontWeight: "normal", fontStyle: "normal", lineHeight: 26, letterSpacing: -0.2, color: Colours.P_80, },});