I'm still very new to React and probably Swiper, too, I'm trying to implement it into my app, but I don't know why I can't update my current active index state whenever I change the slide. I don't know what I did wrong, I hope someone can give me some newbie explanation.
My flow: Whenever I change the slide, it'll get the new current index
and set it into the swiperState
, so the state will be updated.
Here's my code:
import { useState, useEffect } from "react"
import './home.css'
import { supabase } from '../../supabaseClient'
import { Swiper, SwiperSlide } from 'swiper/react'
import SwiperCore, { Pagination,Navigation } from 'swiper';
import 'swiper/css'
SwiperCore.use([Pagination,Navigation]);
function Home(){
const [animeDetail, setAnimeDetail] = useState([])
const [swiperIndex, setSwiperIndex] = useState(0)
useEffect(async ()=>{
fetchAnime()
}, [])
async function fetchAnime() {
const { data } = await supabase
.from ('anime')
.select ()
setAnimeDetail(data)
}
return (
<>
<div className="spacer">
</div>
<div className="home-section">
<h2>Home Page</h2>
<Swiper
initialSlide = {4}
centeredSlides={true}
slidesPerView={7}
spaceBetween={10}
loop={true}
pagination={false}
// I use onActiveIndexChange to track current active index
// and update its state using setSwiperIndex
onActiveIndexChange={index => setSwiperIndex(index)}
navigation={true} className="mySwiper">
{animeDetail.map((element, i)=>
(
<SwiperSlide key = {i}>
<img src={element.anime_image}/>
</SwiperSlide>
)
)}
</Swiper>
{/* I tried to call it down here to see whenever I change my slide, will it update the index through console log, but it doesn't */}
{console.log(swiperIndex)}
</div>
</>
)
}
export default Home
CodePudding user response:
As I can see onActiveIndexChange
method gives you a SwiperCore object, not the current index. So you should update your state with activeIndex
attribute of that object. Like
onActiveIndexChange={(swiperCore) => { setSwiperIndex(swiperCore.activeIndex); }}