Home > database >  How to update my index when I first render my page using React?
How to update my index when I first render my page using React?

Time:12-28

How can I update my index the first time I render the page, everything is working as I want but the first time it renders it returns the undefined so I can't get the info at the first time rendering.

First-time refresh/ render the page:

First render

After swipe or click next and then return to the previous item, it'll update correctly.

Render again

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()

    useEffect(async ()=>{
        fetchAnime()
    }, [])

    async function fetchAnime() {
        const { data } = await supabase
            .from ('anime')
            .select ()
            setAnimeDetail(data)
    }

    return (
        <>
        <div className="spacer">
            &nbsp;
        </div>
        <div className="home-section">

            <h2>Home Page</h2>

            <Swiper
            runCallbacksOnInit = {true}
            centeredSlides={true}
            slidesPerView = {7}
            spaceBetween={10}
            loop={false}
            pagination={false} 
         // I set my index to the state here
            onActiveIndexChange={(swiperCore) => {setSwiperIndex(swiperCore.realIndex)}}
            navigation={true} className="mySwiper">
                {animeDetail.map((element, i)=> 
                    (
                    <SwiperSlide key = {i}>
                        <img src={element.anime_image}/>
                    </SwiperSlide>
                    )
                    )}
            </Swiper>

        {/* Current index of active slide */}
        {console.log(swiperIndex)}
        {/* The specific info contains on active slide */}
        {console.log(animeDetail[swiperIndex])}
        {/* An array list contains each anime */}
        {console.log(animeDetail)}
        </div>
        </>
    )

}
export default Home

Edit: After I tried @Dae Hyeon Mun's solution, the problem is still there.

The code

I still get the undefined when the first time renders/refresh the page.

undefined value

CodePudding user response:

You should start with 0 as the initial state value for the index:

// const [swiperIndex, setSwiperIndex] = useState() // before
const [swiperIndex, setSwiperIndex] = useState(0) // after

On the first render, you will only have the data that you provide as the initial values to your state (empty array and 0). useEffect doesn't run until after the first render.

CodePudding user response:

Try fix code as below

 useEffect(async () => {

    const { data } = await supabase
        .from ('anime')
        .select()

    setAnimeDetail(data)
    }, [])

   if (animeDetail.length === 0) {
     return <div>Loading</div>;
   }
   .... rendering // 
  • Related