Reputation: 724
I want to get the current slide index, so I'm trying to consume the CarouselContext. This is what I got and used from the documentation:
const carouselContext = useContext(CarouselContext);
const [currentSlide, setCurrentSlide] = useState(carouselContext.state.currentSlide);
useEffect(() => {
function onChange() {
setCurrentSlide(carouselContext.state.currentSlide);
console.log(currentSlide)
}
carouselContext.subscribe(onChange);
return () => carouselContext.unsubscribe(onChange);
}, [carouselContext]);
return <CarouselProvider style={{ height: 'fit-content', marginLeft: '10%', marginRight: '10%'}}
isPlaying={true}
infinite={true}
naturalSlideHeight={125}
naturalSlideWidth={100}
isIntrinsicHeight={true}
lockOnWindowScroll={true}
totalSlides={3}
visibleSlides={1}
currentSlide={1}
>
<Slider style={{padding: '19px 260px'}}>
<Slide index={0}>
<TestimonialCard/>
</Slide>
<Slide index={1}>
<TestimonialCard/>
</Slide>
<Slide index={2}>
<TestimonialCard/>
</Slide>
</Slider>
</CarouselProvider>
But when I run this code, this is what I get:
TypeError: Cannot read properties of undefined (reading 'state')
Clearly, carouselContext is undefined, and trying to read carouselContext.state.currentSlide is giving me this error. How can I fix this?
Upvotes: 4
Views: 1244